How to add two bytes together in Java, with wrap around if there is overflow

accountantToDev :

I need to add up all of the bytes in a byte array consisting of only ASCII characters using one's complement binary addition, storing the result as a single byte checksum.

I am trying to start with the basics by figuring out how to add just 2 bytes together, but have no idea how to "wrap around" if there is an extra bit when adding the two binary values.

I have made a tester program so I can play around with different values. In the below example I am trying to add two binary numbers, each representing the decimal value 255.

byte b1 = (byte) 255;
String s1 = String.format("%8s",Integer.toBinaryString(b1 & 0xFF)).replace(' ', '0');
System.out.println("byte 1: " + s1); // 1111111

byte b2 = (byte) 255;
String s2 = String.format("%8s",Integer.toBinaryString(b2 & 0xFF)).replace(' ', '0');
System.out.println("byte 2: " + s2); // 1111111

byte sum = 0;

sum += b1;
sum += b2;

String s3 = String.format("%8s", Integer.toBinaryString(sum & 0xFF)).replace(' ', '0');
System.out.println("sum of byte 1 and byte 2: " + s3); // should be 1111111

I expected the output to be:

byte 1: 11111111
byte 2: 11111111
sum of byte 1 and byte 2: 11111111

but the actual output is:

byte 1: 11111111
byte 2: 11111111
sum of byte 1 and byte 2: 11111110

How do I wrap around the extra bit so that I get the correct result?

Jacob G. :

Because you're only working with byte, you can store the result of your addition in a larger primitive type, such as an int. By doing this, you'll have easy access to the overflow bit, which you can extract (using bitwise operations) and add to the existing sum:

int sum = b1 + b2;
sum += (sum >> 8) & 1;
String s3 = String.format("%8s", Integer.toBinaryString(sum & 0xFF)).replace(' ', '0');
System.out.println("sum of byte 1 and byte 2: " + s3); // should be 11111111

If the value of the overflow bit is 0, then nothing happens. But if it's 1, overflow occurred and the bit will wrap around.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=78989&siteId=1