Perl shift bit problem -
i have problem when try shift bit negative number perl. example:
printf("%d", (-10) >> 2); this method print: 1073741821
with same condition, when try javascript:
document.write('test: ' + (-10 >> 2) + '<br>'); the output -3
i understand different between perl , javascripts. perl have problem shifting bit negative number?
thank much.
perl uses unsigned binary right shift. if perl runs on 32-bit architecture, following:
-10 == -0xa == 0xfffffff6 0xfffffff6 >> 2 == 0x3ffffffd == 1073741821 unsigned binary right shift means highest (rigtmost) bits of result become 0.
javascript uses sign-extending binary right shift. javascript shifts treat both input , output 32 bit integers. get:
-10 == -0xa == 0xfffffff6 -3 == -0x3 == 0xfffffffd 0xfffffff6 >> 2 == 0xfffffffd == -3 sign-extending binary right shift means highest (rigtmost) bits of result copied highest bit of original value.
as tim henigan said in answer, it's possible sign-extending binary right shift perl, specifying use integer;. example:
{ use integer; printf "%d 0x%x\n", (-10) >> 2, (-10) >> 2; #: -3 0xfffffffd } printf "%d 0x%x\n", (-10) >> 2, (-10) >> 2; #: 1073741821 0x3ffffffd
Comments
Post a Comment