Rajat Gupta
Rajat Gupta

Reputation: 26597

Converting integers into bytes

How do the following numbers, on byte conversion give the results on right hand side ? I guess when you convert an integer to a byte array, it should convert each of the digit of that number into its correponding 4 byte array. But here's what cannot understand..

727 = 000002D7

1944 = 00000798

42 = 0000002A

EDIT: I was reading a blog where I found these following lines:-

If we are working with integer column names, for example, then each column name is 4 bytes long. Lets work with column names 727, 1944 and 42.

The bytes associated with these three numbers:

727 = 000002D7

1944 = 00000798

42 = 0000002A

link to this blog: http://www.divconq.com/2010/why-does-cassandra-have-data-types/

Upvotes: 0

Views: 801

Answers (1)

user177800
user177800

Reputation:

Solution

The following will give you the exact output as in your example:

public class Main
{
    public static void main(final String[] args)
    {
        System.out.format("%08X\n", 727);
        System.out.format("%08X\n", 1944);
        System.out.format("%08X\n", 42);
    }
}

and here is the expected output:

000002D7
00000798
0000002A

Explanation

How the Formatter works, the format from right to left string says, x = format as hexadecimal, 08 = pad to the left eight characters with 0 and the % marks the beginning of the pattern.

You can also use String.format("%08X", 727); to accomplish the same thing.

Upvotes: 1

Related Questions