[Newbies] Storing a negative SmallInterger in a ByteArray
Bert Freudenberg
bert at freudenbergs.de
Mon Mar 5 10:52:01 UTC 2007
On Mar 5, 2007, at 11:01 , Mispunt wrote:
> Hi people,
>
> I am a bit confused...
Maybe you just missed the classes where they talked about bits,
bytes, words, and how they relate to numbers? ;)
> I am working on an implementation to communicate with the Lego
> Mindstorms NXT. Al works fine, except I have to store some negative
> numbers in the ByteArray that should be send to the NXT. Everytime I
> try, I get an improper store into indexable object.
>
> Is it possible to store negative values in a ByteArray?
Sure. It's just bits after all. There are no "negative" bits, a bit
is 0 or 1. It depends on the interpretation of the bit pattern you
are sending, the receiving side might interpret some bit patterns as
negative values and others as positive values.
The most common convention is to use "two's complement", see
http://en.wikipedia.org/wiki/Two's_complement
E.g., in 8-bit two's complement ("signed char" in C), the bit pattern
"11111111" stands for -1, whereas as an 8-bit "unsigned char" with
the same "11111111" pattern would be interpreted as 255.
You just have to find out how negative values are represented in the
NXT format, like signed chars, signed shorts, signed int or whatever.
Then use the appropriate accessor to put the right bit pattern for
the value into the byte array:
byteArray signedByteAt: byteOffset put: value "8 bits"
byteArray signedShortAt: byteOffset put: value "16 bits"
byteArray signedLongAt: byteOffset put: value "32 bits"
Note these methods use the FFI plugin because they are designed to
work with C code.
- Bert -
More information about the Beginners
mailing list