Win a copy of Pragmatic AI this week in the Artificial Intelligence forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Junilu Lacar
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Ganesh Patekar
  • Tim Moores
  • Pete Letkeman
  • Stephan van Hulst
Bartenders:
  • Carey Brown
  • Tim Holloway
  • Joe Ess

Automatic casting  RSS feed

 
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).
 
author
Sheriff
Posts: 23571
138
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!