0

I have declared a numpy ndarray containing a single unsigned integer:

import numpy as np  
foo=np.array([3600000],dtype='uint32')

I would like to store this array into a 4 bytes sequence. I have already tested a few options, such as the struct.pack() and struct.pack_into() methods, to no avail. I have also tried the numpy.ndarray.tobytes() method, which converts the content of my array into a bytes object:

bar=np.ndarray.tobytes(foo)

Alas, the ouput byte object has a length of 4 bits! How can I control the number of bits of my output bytes sequence?

Many thanks for your help!

Sheldon
  • 4,084
  • 3
  • 20
  • 41
  • *"Alas, the ouput byte object has a length of 4!"* I'm confused. The array `foo` contains one element of type `uint32` (i.e. an unsigned 32 bit integer). That's four bytes. Why are you disappointed that the length of `bar` is 4? – Warren Weckesser Jul 27 '18 at 21:01
  • Hi Warren! Thanks for your reply; the output byte object has a length of 4 bits! Sorry for the confusion; I will edit my question to clarify this. – Sheldon Jul 27 '18 at 21:03
  • 1
    `bar` is a `bytes` object with 4 *bytes*, not bits. – Warren Weckesser Jul 27 '18 at 21:04
  • Thanks Warren! This definitely answers my question! – Sheldon Jul 27 '18 at 21:12
  • Not really related, but it's possible to convert it in the reverse direction `numpy.ndarray(buffer=<...>, shape=<...>, dtype=<...>)` – user202729 Dec 31 '20 at 09:09

1 Answers1

0

As pointed out by Warren Weckesser, the length of a bytes object is given in bytes, not in bits. So in this case, bar indeed has a length of 4 bytes.

Sheldon
  • 4,084
  • 3
  • 20
  • 41