tags:

views:

59

answers:

3

I am doing a assignment about this.

For Eaxmple: I have a message (String), and the length is 302 in dec, 12e in hex.

String message = "THE MESSAGE BODY";
int lengthOfMessage = number.length(); // 302
String lengthOfMessageInHex = Integer.toHexString(lengthOfMessage); // 12e

Now, I need to change the lengthOfMessageInHex from "12e" to "0000012e".

lengthOfMessageInHex = ("00000000" + lengthOfMessageInHex)
               .substring(lengthOfMessageInHex.length()); // 0000012e

And Now I would like to store 00 00 01 2e to a new byte[4].

How can I do it??

Thank You.

+2  A: 

If you have the original integer, why would you not just use that instead of a string, something like:

byt[0] = lengthOfMessage / 16777216;            // most significant.
byt[1] = (lengthOfMessage % 16777216) / 65536;
byt[2] = (lengthOfMessage % 65536) / 256;
byt[3] = lengthOfMessage % 256;                 // least significant.

If, for some reason you don't have access to the original integer (if the string is stored in a text file or sent across the wire), you can use parseInt to get the integer back before using the above method:

string s = "0000012eRestOfMessage";
int x;
try {
    x = Integer.parseInt (s.substring (0,8), 16);
} catch (Exception e) {}

Alternatively, you could bypass the middle step altogether with something like:

string s = "0000012eRestOfMessage";
byte byt[4];
try {
    for (int i = 0; i < 4; i++) {
        int x = Integer.parseInt (s.substring (i*2,2), 16);
        byt[i] = (byte)((x > 127) ? x - 256 : x);
    }
} catch (Exception e) {}
paxdiablo
lengthOfMessage is an int, I cannot change it to byte
Roy
You're not turning lengthOfMessage into an int, you performing calculations on it to get bits that are less than 256. Then you can just cast those to a byte, keeping in mind that you may need to map 0..255 to 0..-1.
paxdiablo
A: 

I think I would prefer the solution of paxdiablo, but an alternative could be made by cutting up your string in short strings of 2 (e.g. 00 00 01 2e = 4 separate strings) and using Byte.valueOf(String s, int radix) thereby creating a Byte, and then using byteValue() on that Byte to get the byte.

extraneon
"radix" in Byte.valueOf(String s, int radix) will give 16 or other?
Roy
OH yes, I can do it!!!Thank you.
Roy
A: 

I would just do this...

        byte[] byt = new byte[4];    
        byt[0] = Byte.parseByte(lengthOfMessageInHex.substring(0, 2), 16);
        byt[1] = Byte.parseByte(lengthOfMessageInHex.substring(2, 4), 16);
        byt[2] = Byte.parseByte(lengthOfMessageInHex.substring(4, 6), 16);
        byt[3] = Byte.parseByte(lengthOfMessageInHex.substring(6, 8), 16);
johnbk
Roy