I want to initialize the value of byte to -1. When I just use byte num = -1
the value ends up being a decimal 255. I've also tried int8_t number = -1
and then byte num = number
but this didn't work either.
3 Answers
A byte can't be -1. A byte can only store numbers between 0 and 255 inclusive.
Depending on the range of your numbers you could use a char
(-128 to +127) or an int
(-32768 to +32767).
Simply -1 can't be a byte. A byte is a number from 0-255. -1 is below 0. The Arduino reference defines a byte as "A byte stores an 8-bit unsigned number, from 0 to 255.".
As the other two users have already mentioned: A byte can only store a number between 0-255, which obviously means that -1 can't be stores as a byte.
I suggest storing it as a positive number, and then when you want to use it just multiply it by -1, which will turn it into a negative one.
Example to convert positive number as a byte to a negative number:
negativeNumber = positiveNumberStoredAsByte * -1
byte
cannot have the value -1, it can store a pattern of bits which could mean -1 when interpreted instead as a signed type, for exampleint8_t
. On a 2's complement machine like an Arduino the bits that mean -1 in anint8_t
mean 255 in abyte
. This kind of thing comes up often in communications when you have an array of bytes that contains the data of fields of other types. However, you have to be careful when forcibly casting types as the rules of behavior that apply have various gotchas for the unwary, especially if you also cast to a type of different width.