This week's giveaway is in the Java/Jakarta EE forum.We're giving away four copies of Java EE 8 High Performance and have Romain Manni-Bucau on-line!See welcome thread
Win a copy of Java EE 8 High Performance this week in the Java/Jakarta EE forum!
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Cast a long into a byte - please explain

Ranch Hand
Posts: 327
When I cast a long into an byte, and the long is larger than the byte, can someone show me what is happening in the background?
long l = 130;
byte b = (byte)l;
I know that the byte is widened to an integer type, but not sure what else is happening to get the answer -126.
Can someone tell me if this is right?
130 in binary =
0000 0000 0000 0000 0000 0000 1000 0010
what happens next?

mister krabs
Ranch Hand
Posts: 13974
A byte is 8 bits so only the last 8 bits are put in the byte:
1000 0010
Since it starts with a 1 we know it is a negative number. Do 2's compliment and you get 126.

Ranch Hand
Posts: 1258
In case "The Saint" didn't clear that all up for you, the compiler will simply truncate your long value to make it fit into a byte's 8-bit size.
Since a long is a signed 32-bit integral type and your byte is a sad 8-bit integral type, it just chops off the left-most 24 bits, leaving you with the 1000 0010 binary byte.
Which, as the saint so kindly noted comes out to your -126 after a few minutes of cursing those days you slept in the back of your undergrad CS classes after you do the 2s complement.
To correct your post then ... the byte is never really "widened" to an int primitive. The truncated long value is actually placed into the byte.

Greenhorn
Posts: 7

Originally posted by Nathaniel Stoddard:
In case "The Saint" didn't clear that all up for you, the compiler will simply truncate your long value to make it fit into a byte's 8-bit size.
Since a long is a signed 32-bit integral type and your byte is a sad 8-bit integral type, it just chops off the left-most 24 bits, leaving you with the 1000 0010 binary byte.
Which, as the saint so kindly noted comes out to your -126 after a few minutes of cursing those days you slept in the back of your undergrad CS classes after you do the 2s complement.
To correct your post then ... the byte is never really "widened" to an int primitive. The truncated long value is actually placed into the byte.

Just to Correct this post Long is 64 bit Integral Type Not 32 bit Integral
Priyank

 Willie Smits increased rainfall 25% in three years by planting trees. Tiny ad: The WEB SERVICES and JAX-RS Course https://coderanch.com/t/690789/WEB-SERVICES-JAX-RS