I would have like to know when I wrote the chapter in deepinto pharo about 2 complement... Stef
(These kinds of questions should be asked on pharo-users@lists.pharo.org)
You can only represent positive numbers as ByteArrays, because to represent negative numbers you have to decide how to do that. The most common solution is to use 2-complement. To do this you also need to decide on the number of bytes to use.
Here is an example using 4 bytes:
| integer size mask | integer := -123. size := 4. mask := (2 raisedTo: size * 8) - 1. (mask bitAnd: ((integer abs bitXor: mask) + 1)) asByteArrayOfSize: 4.
=> #[255 255 255 133]
=> FF FF FF 85
The reverse is:
| integer size mask | integer := #[255 255 255 133] asInteger. size := 4. mask := (2 raisedTo: size * 8) - 1. (mask bitAnd: ((integer abs bitXor: mask) + 1)) negated
This is for negative numbers.
Positive numbers need not be 2-complemented.
When decoding, integers < (2 raisedTo: (size * 8) - 1) are negative.
HTH,
Sven
I was going to complain about expecting such niceties as a built in 2s-complement rather than program it myself (I am a bit rusty on such matters), but when I look what should I find?
(-123 asTwosComplement: 16rFFFFFFFF) asByteArray. "=> #[255 255 255 133]"
cheers -ben That is nice indeed, I didn't that existed. Very handy.
I don't like that there are no tests ;-)