Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Perl shift-right operator (>>) 1

Status
Not open for further replies.

ThomVF

Programmer
Feb 8, 2001
270
US
[I am using ActiveState 5.6 on Win2K]
I have a binary char assigned to a variable and am trying to do a right-shift on it, but getting weird results...

# $divLByt is left-byte of a 2 char binary string
my $ordval = ord($divLbyt);

print ("Ord of DivLeftByte = [$ordval]\n");
# Prints "84" (0101:0100)

# Shift $DivLbyt to the right by 1 position
$divLbyt >>= 1;

$ordval = ord($divLbyt);
print ("\nOrd of DivLeftByte = [$ordval]\n");
# Prints "48" (0011:0000) but I expect "42" (0010:1010)

Anyone know if ">>=" has problem on Win2K platforms ?
Help!
 
The problem is that the shift operators do NOT work on strings, only on integers! What is happening is that perl is taking the integer value of $divLbyt, which is 0 since it doesn't contain an integer, and then it is taking the ord or 0, which is 48.

What you should be doing is shifting the integer value of the first char of $divLbyt, which is what you have in $ordval. Try changing your code to this:
Code:
# $divLByt is left-byte of a 2 char binary string
my $ordval = ord($divLbyt);

print ("Ord of DivLeftByte = [$ordval]\n");
# Prints "84" (0101:0100)

# Shift $DivLbyt to the right by 1 position
$ordval >>= 1;

print ("\nOrd of DivLeftByte = [$ordval]\n");
# Should now print "42" (0010:1010)
Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
 
Note: Don't feel bad, I read over the description for the shift operators in the perlop man page several times before I noticed the last sentence the description for both << and >>. It says quite clearly &quot;Arguments should be integers&quot;. Guess I should read the docs more carefully the FIRST time! :~/ Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
 
Thanks very much for the speedy reply - I hate posting questions here but I was desperate and rushed (too much going on at once) - I hope I can return the favor to you, or someone else.
 
I love posting things here, and I love helping people out. Don't worry about returning the favor to me, just help someone else out. That's what we're here for. Remember:

&quot;What goes around, comes around.&quot;

It works!
Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top