Help coderanch get a
new server
by contributing to the fundraiser
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Jeanne Boyarsky
• Ron McLeod
• Paul Clapham
• Liutauras Vilda
Sheriffs:
• paul wheaton
• Rob Spoor
• Devaka Cooray
Saloon Keepers:
• Stephan van Hulst
• Tim Holloway
• Carey Brown
• Frits Walraven
• Tim Moores
Bartenders:
• Mikalai Zaikin

# Trying to understand Casting

Greenhorn
Posts: 11
1
• Number of slices to send:
Optional 'thank-you' note:
why does this result in -128?
int a = 128;
byte b = 0;
b =(byte) a;

why does this result in 44
int a = 300;
byte b = 0;
b =(byte) a;

I think I understand the fact that you wouldn't cast this way. Just trying to understand the output. If I am correct you would use casting when you have something like this
int a = 50;
byte b = 0;
b = (byte) a * 2;
Although 50 * 2 = 100 which is in the range of byte, the use of the operator automatically converts the expression to an interger. Thanks for whatever you care share.

author
Posts: 23956
142
• Number of slices to send:
Optional 'thank-you' note:

Chad McAte wrote:why does this result in -128?
int a = 128;
byte b = 0;
b =(byte) a;

The bit pattern for a 128 value int is ... 0000 0000 0000 0000 0000 0000 1000 0000. When you explicitly cast it to a byte, even though this value doesn't fall into the range of the byte, the compiler will use the same bit pattern (for the lower 8 bits only).  And under twos complement rules, the bit pattern of 1000 0000, as a byte is -128.

Henry

Henry Wong
author
Posts: 23956
142
• Number of slices to send:
Optional 'thank-you' note:

why does this result in 44
int a = 300;
byte b = 0;
b =(byte) a;

The bit pattern for a 300 value int is ... 0000 0000 0000 0000 0000 0001 0010 1100. When you explicitly cast it to a byte, even though this value doesn't fall into the range of the byte, the compiler will use the same bit pattern (for the lower 8 bits only).  And under twos complement rules, the bit pattern of 0010 1100, as a byte is 44.

Henry

 All of life is a contant education - Eleanor Roosevelt. Tiny ad: We need your help - Coderanch server fundraiser https://coderanch.com/t/782867/Coderanch-server-fundraiser