I don't know why the number of elements changes when the type is converted to dtype view

Asked 1 years ago, Updated 1 years ago, 318 views

I don't know why the number of elements changes when the type is converted to numpy type view

arr = np.zeros(2, dtype=np.uint16)

arr

array([0, 0], dtype=np.uint16)

arr.view(np.uint8)

array([0, 0, 0, 0], dtype=uint8)

arr.view(np.uint32)

array([0], dtype=uint32)

I changed the type from 1.uint16 to uint8, but I don't understand why [0,0] increased the element to [0,0,0,0]. I just changed the type...

Even if you change the tie from 2.uint8 to uint32, why only one comes out as [0]...

Does the type change affect the number of elements? Please tell me the reason why it changes so much different <

python numpy

2022-11-03 00:00

1 Answers


>>> arr = np.zeros(2, dtype=np.uint16)
>>> arr
array([0, 0], dtype=uint16)
>>> arr.view(np.uint8)
array([0, 0, 0, 0], dtype=uint8)
>>> arr
array([0, 0], dtype=uint16)


>>> arr[0] = 0xabcd
>>> arr
array([43981,     0], dtype=uint16)
>>> arr.view(np.uint8)
array([205, 171,   0,   0], dtype=uint8)
>>> hex(205)
'0xcd'
>>> hex(171)
'0xab'


>>> arr[0] = 0xabcd
>>> arr[1] = 0x1234
>>> arr
array([43981,  4660], dtype=uint16)
>>> viewhex = lambda l: list(map(hex, l))


>>> viewhex(arr)
['0xabcd', '0x1234']
>>> viewhex(arr.view(np.uint8))
['0xcd', '0xab', '0x34', '0x12']
>>> viewhex(arr.view(np.uint32))
['0x1234abcd']


2022-11-03 00:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.