Home > Mobile >  Why can I bitwise OR two strings as if they were binary numbers?
Why can I bitwise OR two strings as if they were binary numbers?

Time:04-30

I was trying to write a Perl program that would take in two strings representing binary numbers (i.e. consisting of only the characters "1" and "0") as input and print out the result of bitwise ORing the two numbers together (printing the result in binary as well).

In doing so, I created the following program which does exactly this, but I am struggling to understand exactly why it works:

my $a = "1000100101101";
my $b = "0100111000101";
print($a | $b); # prints "1100111101101"

I know that perl automatically convert strings into numbers when used in a number-like context, but it has always been the case that it converts such strings into base-10 numbers.

Why does this program seemingly perform a bitwise OR on two strings of binary digits?

CodePudding user response:

When using the bitwise feature,

  • | takes two numbers and finds the bitwise OR of them. (Strings are numified.)

  • |. takes two strings and finds the bitwise OR of each same-index characters of the strings. (Numbers are stringified.)

Without the bitwise feature, Perl guesses which one of the above to do for | based on the types of the operands.

You apparently weren't using the bitwise feature. By providing two strings, you ended up perform an OR of each of the same-index characters of the strings.

| and & will work for binary (if the strings are of the same length), but not ^.

CodePudding user response:

The ASCII codes for '0' and '1' are the numbers 48 and 49 respectively. The binary representations of these are 0011_0000 and 0011_0001, which happen to OR correctly. Could be a coincidence, could even be that the ASCII committee designed it that way. Dunno.

If you OR the capital letter 'A' and a space, 0100_0001 and 0010_0000, the result is 0110_0001, i.e., lowercase 'a', just as expected.

  •  Tags:  
  • perl
  • Related