简体   繁体   English

将11字节的十六进制字符串转换为大小为16的字节数组

[英]Convert 11 byte hex string to byte array of size 16

I have a hex string of 11 bytes "0017333032CD4900186F41" . 我有一个11字节的十六进制字符串"0017333032CD4900186F41" I have to convert this string to a byte array and I am doing it fine and getting the correct result. 我必须将此字符串转换为字节数组,并且做得很好,并获得正确的结果。 However, following a particular message format, I would like to convert this hex string to a byte array of size 16 instead of 11. Is this possible? 但是,按照特定的消息格式,我想将此十六进制字符串转换为大小为16而不是11的字节数组。这可能吗?

I tried hex.getBytes("UTF-8") and this gave me an array of size 32. Is it possible to have a 11 byte hex string as a byte array of 16? 我尝试了hex.getBytes("UTF-8") ,这给了我一个大小为32的数组。是否有一个11字节的十六进制字符串作为16字节的数组?

This requirement is in Java for a BlackBerry app. BlackBerry应用程序的Java中有此要求。 This has been successfully implemented in Android and iPhone. 这已在Android和iPhone中成功实现。 Android is making use of the ByteConverter lib in Basic4Android to get the desired result: Android正在使用ByteConverter中的ByteConverter lib获得所需的结果:

Dim data() As Byte
data = Bconv.HexToBytes(data_hex)

A hexadecimal string represents a byte with 2 digits (16² = 256). 十六进制字符串表示一个带有2位数字的字节(16²= 256)。

so pad the string data_hex to the right with zeroes till it has a length of 2*16 = 32. Then do the HexToBytes conversion. 因此,将字符串data_hex用零data_hex到右边,直到其长度为2 * 16 =32。然后执行HexToBytes转换。

try 尝试

String s = "0017333032CD4900186F41";
BigInteger bi = new BigInteger(s, 16);
byte[] a1 = bi.toByteArray();
byte[] a2 = new byte[16];
System.arraycopy(a1, 0, a2, 16 - a1.length, a1.length);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM