[comp.lang.perl] hex numbers, bit ands, shifting

gregs@well.sf.ca.us (Greg Strockbine) (03/08/91)

 I need some help with this one.

I'm trying to write a perl script to interpret hex memory dumps.
How do I deal with hex numbers and shifting and bitwise anding, I'm
getting confused, I have perl 3.0, patch level 12, Vax 6420.

I fed "B000" to a perl script that did something like this:
$word = "B000";
print ($word & 0xF000) >> 12, "/n";
and I get 0.  How come I didn't get B?

Any help is greatly appreciated.
greg strockbine, dataproducts, woodland hills, ca.

tchrist@convex.COM (Tom Christiansen) (03/08/91)

From the keyboard of gregs@well.sf.ca.us (Greg Strockbine):
:
: I need some help with this one.
:
:I'm trying to write a perl script to interpret hex memory dumps.
:How do I deal with hex numbers and shifting and bitwise anding, I'm
:getting confused, I have perl 3.0, patch level 12, Vax 6420.
:
:I fed "B000" to a perl script that did something like this:
:$word = "B000";
:print ($word & 0xF000) >> 12, "/n";
:and I get 0.  How come I didn't get B?

You have two problems here.  

The first is you assigned $word the string "B000", instead of 
the numeric hex constant 0xB000; the string "B000" is numerically 0.
This is related to the new question on the FAQ I posted yesterday.

The second is that you have tricked the print operator into behaving 
like a function call.  Or perhaps it's tricked you. :-)  Remember: if
it looks like a function call (as in having a paren ANYWHERE after it)
then it will be treated as such.  What you have is treated as follows:

    (print($word & 0xF000) >> 12), "\n";

Surely not what you want.  Try this:

    $word = 0xB000;
    print(($word & 0xF000) >> 12, "\n");
or
    print +($word & 0xF000) >> 12, "\n";


Read the verbiage on page 79 of the book for details.  This is 
certainly a common novice goof, although it's not listed as such.
Maybe it should be on the FAQ?


--tom