ramp icon indicating copy to clipboard operation
ramp copied to clipboard

[feature request] Convert from/to bytes

Open Stebalien opened this issue 10 years ago • 3 comments
trafficstars

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.

Stebalien avatar Jun 10 '15 01:06 Stebalien

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.

Aatch avatar Sep 26 '15 02:09 Aatch

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?

Aatch avatar Sep 26 '15 03:09 Aatch

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.

Stebalien avatar Sep 27 '15 22:09 Stebalien