Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Bit Shifting Negative vs positive values

I was recently going over bit shifting and was wondering why in the below iPython output, shifting the value -1 vs shifting the value 4294967295 yielded different results?

In [30]: val = -1

In [31]: print "hex x %d 0x%08X" % (val, val & 0xffffffff)

hex x -1 0xFFFFFFFF

In [32]: val = val >>22

In [33]: print "hex x %d 0x%08X" % (val, val & 0xffffffff)

hex x -1 0xFFFFFFFF

In [34]: val = 4294967295

In [35]: print "hex x %d 0x%08X" % (val, val & 0xffffffff)

hex x 4294967295 0xFFFFFFFF

In [36]: val = val >>22

In [37]: print "hex x %d 0x%08X" % (val, val & 0xffffffff)

hex x 1023 0x000003FF

I would really appreciate any clarification, thanks.

like image 518
aaron-prindle Avatar asked Apr 12 '26 21:04

aaron-prindle


1 Answers

4294967295 is 0x0...0FFFFFFFF. -1 is 0xF...FFFFFFFF. Forever.

like image 53
Ignacio Vazquez-Abrams Avatar answered Apr 15 '26 11:04

Ignacio Vazquez-Abrams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!