Bulk Emailing

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Saturday, 15 October 2011

Its about Bytes in Java

Posted on 05:21 by Unknown
I have seen people struggle in handling data in Java when it reaches at the byte level. As Java doesn't support any concept of Un-signed data type, so it makes things more complex. So thought lets share my understanding.

Java stores negative values in 2's complement format and to get absolute value of any negative number you need to type cast variable with higher byte value datatype. In simple word, to get absolute value of -ve byte data type variable it need to type cast/upgrade to some other date type (e.g. short/int) having more number of bytes and.
Example,
byte mSample = 142;
If you print its value, it will show -114. So, why does the JVM shows -114 ?
Binary of 142 : 1 0 0 0 1 1 1 0. The left most bit is Signed bit, so JVM considers this number as -ve value and converts it into 2's Complement, which means, 0 1 1 1 0 0 1 0 = - 114. So, its simple, right ?
So, to get absolute value of mSample, we need to type cast it to higher byte enabled data type e.g. int.
int abmSample = 0xFF & (int) mSample;
Why do I need to do AND operation with 0xFF ?
0xFF makes remaining bits apart from first 1 byte value to 0. So, you get absolute value i.e. 142.

I have written an utility Class ByteUtils.java which provides methods to convert byte array to Hexadecimal values, Integers and Long. This sample also considers byte ordering i.e. Little and Big endian. Hope this small write up helps people in understanding byte level data handling in Java.
Email ThisBlogThis!Share to XShare to Facebook
Posted in | No comments
Newer Post Older Post Home

0 comments:

Post a Comment

Subscribe to: Post Comments (Atom)

Popular Posts

  • CityWeather
    Update: Release 1.1 has been uploaded. It will now provide weekly forecast of your selected cities. Download   CityWeather is an Android...

Blog Archive

  • ►  2013 (6)
    • ►  September (2)
    • ►  May (1)
    • ►  April (1)
    • ►  February (1)
    • ►  January (1)
  • ►  2012 (4)
    • ►  July (2)
    • ►  March (1)
    • ►  January (1)
  • ▼  2011 (11)
    • ►  November (1)
    • ▼  October (2)
      • Its about Bytes in Java
      • Excel Column Sequence Algorithm
    • ►  August (1)
    • ►  June (1)
    • ►  April (2)
    • ►  March (3)
    • ►  January (1)
  • ►  2010 (27)
    • ►  December (2)
    • ►  November (3)
    • ►  September (2)
    • ►  August (4)
    • ►  July (4)
    • ►  June (7)
    • ►  May (5)
Powered by Blogger.

About Me

Unknown
View my complete profile