Julia equivalent to Python's int.to_bytes

Here is a more general replacement for Python’s to_bytes function, mainly as a learning exercise. The trick is to use bit shift (>>) and mask (&) operations:

julia> function to_bytes(n::Integer; bigendian=true, len=sizeof(n))
           bytes = Array{UInt8}(undef, len)
           for byte in (bigendian ? (1:len) : reverse(1:len))
               bytes[byte] = n & 0xff
               n >>= 8
           end
           return bytes
       end
to_bytes (generic function with 3 methods)

julia> to_bytes(-28, len=7)
7-element Array{UInt8,1}:
 0xe4
 0xff
 0xff
 0xff
 0xff
 0xff
 0xff

julia> to_bytes(2345, len=7)
7-element Array{UInt8,1}:
 0x29
 0x09
 0x00
 0x00
 0x00
 0x00
 0x00

julia> to_bytes(2345, len=7, bigendian=false)
7-element Array{UInt8,1}:
 0x00
 0x00
 0x00
 0x00
 0x00
 0x09
 0x29

However, it’s not clear to me what this function is actually useful for — Julia has much better alternatives for most things that you might want this for (serialization, bit manipulations, etcetera).

3 Likes