# int_to_bytes

Definition: | sequence s = int_to_bytes(atom a, integer size = 4)
Description: | Convert an integer into a sequence of bytes. These bytes are in the order expected on the 386+, i.e. least-significant byte first.
pwa/p2js: | Supported.
Comments: | You might use this routine prior to poking the bytes into memory for use by a machine language program. The integer can be negative. It can also be a full 32/64 bit integer that does not fit into a 31/63 bit Phix integer type, and hence is declared as type atom. The individual byte-values returned are unsigned (0..255), but after poking them into memory you will have the correct (twos complement) representation, and will yield the same (signed) value if passed to bytes_to_int(). The size may be 1, 2, 4, or 8, ie the number of bytes. For values which exceed the specified size, the lower size*8 bits are stored and any higher bits discarded. Values which exceed the Phix definition of integer (ie 31 or 63 bits) but still fit in the specified size (32 or 64 bits) will work fine, but obviously any variable used to store the result from bytes_to_int() will need to be declared as atom. Note however that 32-bit Phix cannot hold a 64-bit integer with full accuracy, even in a variable declared as atom, since atoms on 32-bit have a maximum precision of 53 bits, however there is no attempt to issue any kind of compiler or runtime error or warning that low-bits might get dropped.
Example 1: |
    s = int_to_bytes(999)
    -- s is {231, 3, 0, 0}
Example 2: |
    s = int_to_bytes(-999)
    -- s is {25,252,255,255}
Implementation: | See builtins\machine.e (an autoinclude) for details of the actual implementation.
See Also: | bytes_to_int, int_to_bits, bits_to_int, peek, poke