Search code examples
pythonnumpycastingbyteunsigned-integer

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

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'