2

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.

asked Oct 6, 2016 at 22:44
3
  • 3
    What are you trying to accomplish? Commented 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. Commented 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. Commented 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).

answered Oct 6, 2016 at 22:49
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.".

Nick Gammon
38.9k13 gold badges69 silver badges125 bronze badges
answered Oct 6, 2016 at 22:50
-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 
answered Oct 14, 2016 at 13:04
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.