Search code examples
pythonrustbyteendianness

How to get bytes from an integer? Like Python's .to_bytes call?


I'm looking to get this in Rust:

print(len(x).to_bytes(2, byteorder="little"))
b'\n\x00

How do I get this byte string? I need to send this string in a request, so I need this raw string format. I experimented with {:x}, but this doesn't seem to be the equivalent.


Solution

  • You can get a byte array representing a 16-bit integer in little-endian byte order by using u16::to_le_bytes:

    fn main() {
        let len: u16 = 110;
        let len_bytes: [u8; 2] = len.to_le_bytes();
        println!("{len_bytes:?}");
    }
    
    [110, 0]