开发者

How to change the hex string to 4 byte in java?

I am doing a assignment about this.

For Eaxmple: I have a message (Strin开发者_开发知识库g), 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.


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) {}


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);


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜