1
    byte[] stuffA = {69,96,13,37,-69,-96,-13,-37};
    for(int x = 0; x < stuffA.length; x++){
        if(stuffA[x] < 0){
            System.out.println("Somethin be up yo! ");
            System.out.println("This number be negative! " + (int)stuffA[x]);
            stuffA[x] = (byte)((int)stuffA[x] + 256);
            System.out.println("I added 256 and now stuff is positive yo! " + stuffA[x]);
        }
    }
    return;

When I run this, my output is:

Somethin be up yo! 
This number be negative! -69
I added 256 and now stuff is positive yo! -69
Somethin be up yo! 
This number be negative! -96
I added 256 and now stuff is positive yo! -96
Somethin be up yo! 
This number be negative! -13
I added 256 and now stuff is positive yo! -13
Somethin be up yo! 
This number be negative! -37
I added 256 and now stuff is positive yo! -37

What is happening?

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
Foo Bar
  • 21
  • 2

6 Answers6

1

Quoting Java Language Specification, section 4.2.1:

The values of the integral types are integers in the following ranges: For byte, from -128 to 127, inclusive.

So, -69 + 256 = 187 = 0x000000BB cast to byte is 0xBB = -69.

Andreas
  • 154,647
  • 11
  • 152
  • 247
1

A byte has a range between -128 and 127 (-2^7 to 2^7-1) Adding 256 its like doing a 360 degree turn . Change 256 to 128 in your code and in will show different results

Armando SM
  • 142
  • 5
0

byte is only 8 bits, so can only hold 2^8 = 256 values. It is signed in java so the values are in the range of [-128,127] inclusive.

James Wierzba
  • 16,176
  • 14
  • 79
  • 120
0

A byte can hold 256 differnet values. If you add 256 the byte overflows, and the result stays the same. In java the range is [-128, 127].

AlexWien
  • 28,470
  • 6
  • 53
  • 83
0

A byte can hold 256 different values, so when you add 256 you are making a Rol (Rotate left) 8 times, which returns the same value as previous.

If your desire is to transform -69 in 69, why you simply don't make a stuffA[x] *=-1?

If you really want to reverse the bits, you can use complement operator (~), stuffA[x] = (byte) ~stuffA[x];, but due to the two's complement form, to get the same number as previos you need to add 1,

like stuffA[x] = (byte) ((~stuffA[x]) + 1);

Johnny Willer
  • 3,717
  • 3
  • 27
  • 51
0

byte is 8 bits and integer is 32 bits

basically looking at bits:

byte b = -37 is equivalent to 219(int) whose binary is:

0000 0000 0000 1101 1011

int 256:

0000 0000 0001 0000 0000

adding both will give int value of 475:

0000 0000 0001 1101 1011

now convert it to byte i.e. take LSB 8 bits will be:

1101 1011

which is -37

Hope this explains

abhish_gl
  • 363
  • 1
  • 10