• Post Reply Bookmark Topic Watch Topic
  • New Topic

Automatic casting  RSS feed

 
Shivit Agarwal
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all,

byte b= 0xf1; // 11110001
int i= b; // 11111111 1111111 11111111 11110001

Question is why all other bits in the variable "i" turn to be 1(i.e bold 1's).
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Shivit Agarwal:
Hello all,

byte b= 0xf1; // 11110001
int i= b; // 11111111 1111111 11111111 11110001

Question is why all other bits in the variable "i" turn to be 1(i.e bold 1's).


That's is how "twos complement" work. The "0xf1" is just a hex representation that the compiler used for your convenience. The byte value, if you printed it out is "-15". For ints, that is the equivalent for "-15". The cast from a byte to an int, is done via the sign extension (this is how twos complement keeps the same value moving from a byte to an int).

Henry
 
Shivit Agarwal
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot sir...thats what i thought, thanks once again for clearing the doubt...

Cheers,
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!