ramp
ramp copied to clipboard
[feature request] Convert from/to bytes
It would be really nice if there were a way to convert Ints from/to byte slices (i.e. MSB/LSB encoded integers). Currently, I'm just doing a bunch of shifts and adds but this is definitely not the best way to do this.
This shouldn't be too hard to add for MSB-encoding, since that's what the lower-level base conversion functions do already. For LSB-encoded, on a little-endian system I should be able to just copy the bytes directly into a new Int. A big endian system is a little more complex, but should just require doing a byte-swap on each word.
Just realized that I'm missing some information for this feature. Ints are stored as signed-magnitude, so that's what would be easiest to encode and decode. Supporting a two's complement representation as well could be possible, though a fair bit more difficult. Are you expecting to convert only non-negative numbers or negative numbers too? If you have negative numbers, how are they represented?
I'm only planning on converting positive numbers. IMO, it's better to just encode the magnitude and let the user handle the sign.
Personally, I'd prefer MSB (I'm sending the numbers over the network) but it would be nice to support both.