Saturday, October 15, 2011

Its about Bytes in Java

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.

Thursday, October 6, 2011

Excel Column Sequence Algorithm

One of my friend came up with a question..."How do you find out the sequence of MS Excel column ?", lets put this in an another way, If I tell you one Excel Sheet column sequence e.g. ABA how do you find out the index of the column e.g. AA is 27th column, AB is 28th column.

So, I thought to put this as an Algo; with this if you have any sequence, you will be able to compute the column number-

Column Number = Alphabet Seq Number (right most) + Alphabet Seq Number * 26 + Alphabet Seq Number * (26*26) + .......... + Alphabet Seq Number (left most) * (p-1 times multiplication of 26)

Where,
Alphabet Seq Number = 1-26, (A = 1 and Z = 26)
p = number of Alphabets in the Column Sequence e.g. for "ABC", p = 3. Here  is C at position 1, B at 2 and A at 3.

So, with the above formula, Column number for ABC = C + B * 26 + A * (26 * 26)  
= 3 + 2 * 26 + 1* (26*26) = 731

So, what about doing the reverse i.e. generate the sequence from column number. To do this, we need to divide the number by 26 and consider the reminders to pick the Alphabet. The sequence of reminders that we get from 731 are 3 (C), 2(B), 1(A), so the Column sequence is "ABC" (last reminder value at the first).

Please find the CalculateExcelColumn.java to generate Column sequence from Column number. Hope the Algo helps...:-)