1

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
  • 3
    What are you trying to accomplish? Oct 7, 2016 at 1:48
  • Note that while a 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 example int8_t. On a 2's complement machine like an Arduino the bits that mean -1 in an int8_t mean 255 in a byte. 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. Oct 16, 2016 at 20:43
  • If you show the code of what you are trying to do, then an appropriate suggestion can be made. Without that, people can only explain the failure and guess at what your goal is. Oct 16, 2016 at 20:47

3 Answers 3

6

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).

4

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.".

-1

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 
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.