• 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:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

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
Posts: 23811
140
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,
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!