Thursday, April 19, 2007

Data Type Conversion in Java

We have all done and still do datatype conversions (eg:from char to int) all the time.Well most of the time in C and C++ the datatype conversions work out very well seldom causing any problems..
But when it comes to data type conversion in Java it works in a different way..Take an instance ..You want to read file in C and in Java..The data is read in form of bytes and later we convert it to int or char using type conversions..This is where the difference between C and java surfaces..When we convert the 8bit byte to (say) 32 bit int ;in C the remaining positions in the byte excluding the original 8bits are replaced by zeros..But if we do the same conversion in Java the remaining bit positions are replaced by FF..The catch is when we want the read byte (which is effectively the last 8 bits) of this int for another calculation, then in C we can use it directly..However when this is done in Java we have to mask the remaining bits with 0xFF if we don't want to end up with a negative value.. In other words whenever we do a type conversion in Java from a lower size datatype to a upper sized one Java fills all the remaining bit locations with FF and not zeros as in C...hope this is of some help to u guyz


1 comment:

nAmZ said...

Good one!

Search

Google