binary - How to perform operation on specific bits in perl -


lets assume have hexadecimal value 0x78. need add 1 first 4 bits ie 3:0 , add 2 last 4 bits ie. [7:4]. further when add 1 0xf should not roll on next value , should stay 0xf. same applies subtraction. approach have tried far is:

$byte=0x78; $byte2 = unpack('b4', $byte); print "byte2 = $byte2 \n"; 

--> here output 1000 have tried extract first 4 bits, , can right shift , extract last 4 bits , perform operation. perform addition or subtraction, wanted convert 1000 hex format can 0x8 +/- 1. tried:

$hex2 = sprintf('%02x', $byte2); print "hex2 = $hex2 \n"; 

--> output 3e8. not understand why 3e8 instead of 8 or 08, since supposed print 2 values in hex format.

in above command when manually enter $hex2 = sprintf('%02x', 0b1000); correct result. perl taking string rather numeric value. there way can convert string binary number? other easier method or approach helpful.

we can each byte anding , shifting:

$byte1 = $byte & 0xf; $byte2 = ($byte & 0xf0) >> 4; printf "byte1: 0x%x\n", $byte1; printf "byte2: 0x%x\n", $byte2;  # prints byte1: 0x8 byte2: 0x7 

addition/subtraction special conditions listed can done on these bytes , new value can reconstructed shifts , addition:

($byte1 < 0xf) ? ($byte1 += 1) : ($byte1 = 0xf); ($byte2 < 0xe) ? ($byte2 += 2) : ($byte2 = 0xf); # or subtraction stuff.  $new_val = ($byte2 << 4) + $byte1; printf "new val: 0x%x\n", $new_val;  # prints new val: 0x99 

you're getting '3e8' because $byte2 '1000', which, when translated hex '0x3e8'.


Comments

Popular posts from this blog

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -

java - JavaFX 2 slider labelFormatter not being used -