Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My byte suddenly becomes a negative number and count down

I have some code that increases a byte by 8 bits every time it passes through my loop. It all goes as expected until I hit 120, then my numbers suddenly become negative.

Code:

byte b = 0;

for(int i = 0; i < 0x100; i += 8) {
    System.out.print(b + " ");
    b += 8;
}

Output:

0 8 16 24 32 40 48 56 64 72 80 88 96 104 112 120 -128 -120 -112 -104 -96 -88 -80 -72 -64 -56 -48 -40 -32 -24 -16 -8

What I want to see:

0 8 16 24 32 40 48 56 64 72 80 88 96 104 112 120 128 136 144 152 160 168 176 184 192 200 208 216 224 232 240 248 256

Does anyone know why it starts counting down after 120 instead of going up to 256?

like image 615
JREN Avatar asked Jul 05 '13 07:07

JREN


People also ask

Can a byte be a negative number?

In C#, a byte represents an unsigned 8-bit integer, and can therefore not hold a negative value (valid values range from 0 to 255 ).

Can C++ bytes be negative?

Negative Numbers. Because Byte is an unsigned type, it cannot represent a negative number.

Can a byte be negative Java?

In Java, byte is an 8-bit signed (positive and negative) data type, values from -128 (-2^7) to 127 (2^7-1) . For unsigned byte , the allowed values are from 0 to 255 .

Can a byte be negative Arduino?

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). Save this answer.


2 Answers

Does anyone know why it starts counting down after 120 instead of going up to 256?

Yes. Java bytes are signed - it's as simple as that. From section 4.2.1 of the JLS:

The values of the integral types are integers in the following ranges:

  • For byte, from -128 to 127, inclusive
  • ...

The easiest way to display a byte value as if it were unsigned is to promote it to int and mask it with 0xff:

System.out.print((b & 0xff) + " ");

(The & operator will perform binary numeric promotion automatically.)

like image 139
Jon Skeet Avatar answered Sep 20 '22 14:09

Jon Skeet


A byte is a signed quantity ranging from -128 to +127. It wraps around to the lowest negative once it reaches 127.

like image 33
Bathsheba Avatar answered Sep 21 '22 14:09

Bathsheba