Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

numpy – casting uint32 to uint8

I have the following code in python using numpy:

import numpy
a = 423
b = numpy.uint8(a)
print(b)

It gives me the result:

b = 167

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I understand that uint8 (unsigned 8-bit integer) can represent values from 0 to 255. What I don’t understand is how numpy does the cut-off or "truncation" of the value 423 to the value 167. Subtracting 255 from 423 (423 – 255) gives me 168 which is off by one. Anybody knows what is the formula used by numpy in numpy.uint8 when the input value is 255 or greater?

>Solution :

Don’t think of it as subtraction, more an application of mod. Simply put, numpy.uint8 (currently) truncates all the bits after the first 8 (i.e. the number 256) starting from the Least Significant Bit and returns the resulting number. Take a look below:

>>> bin(423) 
'0b110100111'
>>> bin(numpy.uint8(423))
'0b10100111'
>>> >>> bin(12345)
'0b11000000111001'
>>> bin(numpy.uint8(12345))
'0b111001'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading