+ 1

Can someone explain this to me? (Casting thingy...)

public class Main { public static void main(String[] args) { int a = 130; byte b = (byte) a; System.out.print(b); } } I already ask this question yesterday but i didn't still understand the answers. First of all i know this will be a "byte overflow" but why does when i cast a "byte" inside my container "b", the output will be -126? How did the compiler arrived -126? I hope someone can explain me to thisetc.

7th Feb 2021, 8:41 PM
Kakai
Kakai - avatar
5 Answers
+ 2
yes: 127 in binary is 01111111 128 in binary is 10000000 129 in binary is 10000001 130 in binary is 10000010 so, for each, if we convert each to signed: 127 = +1111111 (+127) 128 = -0000000 (-0) 129 = -0000001 (-1) 130 = -0000010 (-2) 2-complement of each (invert all bits and add 1): 1111111 => + sign, no complement (127) 0000000 => 1111111 + 1 = 10000000 = 128 0000001 => 1111110 + 1 = 1111111 = 127 0000010 => 1111101 + 1 = 1111110 = 126 ... all are absolute values, where sign need to be prepend (left-most bit ? - : +)
7th Feb 2021, 9:18 PM
visph
visph - avatar
+ 2
this is not strictly a byte overflow, as the int you cast to byte stand in 8 unsigned bits. however, byte store signed 8 bits values, so left-most bit is used as sign (minus if > 127), and others 7 right-most bits are used as 2-complement (because that's the usual way to store negative binary numbers without breaking math operations) 2-complement isn't really human easy understandable (we will read those negative number more easilly with just setting the left-most bit, but we will have a +0 and -0, and we will broke math operations)...
7th Feb 2021, 8:54 PM
visph
visph - avatar
+ 1
Kakai sorry, my previous answer was for c# instead of Java. Java's 'byte' is equivalent to c#'s 'sbyte' In Java, the data type 'byte' is a signed 8 bit data type, meaning it has a total amount of value 'slots' equal to 256 and because it is signed half of the slots are negative. What this means is 'byte' can only have values between -128 and 127(not 128 because 0 counts.) When a value greater than the max value is set it wraps around back to the minimum number by the excess amount. Think of it as a time line where the left and right end aren't infinity but your max and minimum values. (int) 127 => (byte) 127 (int) 128 => (byte) -128 (int) 129 => (byte) -127 See this program output to compare a list of ints to their byte values. https://code.sololearn.com/c6p1X79Um4GT/?ref=app
8th Feb 2021, 12:44 AM
Elijah Brown
Elijah Brown - avatar
0
visph look i have this pattern, If container a = 127, //Output will be 127 If container a = 128 //Output will be -128 If container a = 129 //Output will be -127 If container a = 130 //Output will be -126 And so on... Is that the meaning of ur explaination?
7th Feb 2021, 9:02 PM
Kakai
Kakai - avatar
0
Or something else?
7th Feb 2021, 9:02 PM
Kakai
Kakai - avatar