On Fri, Feb 6, 2015 at 10:48 PM, Sven Van Caekenberghe <s...@stfx.eu> wrote:

> Alejandro,
>
> > On 06 Feb 2015, at 15:10, Alejandro Infante <
> alejandroinfant...@gmail.com> wrote:
> >
> > Hello,
> > I have just found that calling asByteArray for any negative small
> integer returns the same result that the positive small integer. Is it
> supposed to be like that or is it a bug?
> >
> > 1 asByteArray = -1 asByteArray. "true"
> >
> > (1 to: 100000) allSatisfy: [ :int | int asByteArray = int negated
> asByteArray ] “true"
> >
> > Cheers,
> > Alejandro
>
> (These kinds of questions should be asked on pharo-us...@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

Reply via email to