loody wrote: > > I have to compare 2 values which is represented by 2 bytes as 0xffff > and 0x00fe in 2's complement system. > so the difference between them should be -1 - 254 =-255. > but before do such calculation, I have to translate 0xffff as -1. > Is there build-in function in perl for me to use, or should I transfer > it by hand? > below is the method I thought, but it really seems lousy. > > my $tmp_value1="ffee"; > if (hex $tmp_value1 & 0x8000) > { > my $int=int $tmp_value1; > $int -= 2**16; > $tmp_value1=$int; > } > appreciate your help,
The nice thing about twos complement representation is that you can perform addition or subtraction on both signs of number and the result will be correct. The difficulty is that Perl tries to keep every value as accurately as possible, so 0xffff is 65535 and 0x00fe is 254 (as you say) so subtracting the two gives 0xff01 or 65281. But you're using signed 16-bit arithmetic, so you need to throw away all but the least-significant 16 bits and treat them as two's complement. The builtin function 'pack' will do that for you, but I suggest that you wrap it in a subroutine to make things easier. Here's your problem, with the output that you expect. HTH, Rob use strict; use warnings; sub to16bit; my $x = 0xffff - 0x00fe; print to16bit $x; sub to16bit { my $n = shift; my $trimmed = pack 's', $n; return unpack 's', $trimmed; } -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/