java字节操作疑问

时间:2011-03-01 11:49:10

标签: java byte bytearray hex

public final byte[] getParam(String commandName,String memLocation,String dataId){
    byte[] result = new byte[9];
    //"GET_PARAM", "RAM","WATER_OUTLET_TEMP"
    result[0] = START_FRAME.getBytes()[0]; // {
    result[1] = START_FRAME.getBytes()[0]; // {
    result[2] = Integer.toHexString(commandMap.get(commandName)).getBytes()[0]; // 0xD2
    result[3] = Integer.toHexString(dataIdMap.get(dataId)).getBytes()[0];  // 0x1
    result[4] = Integer.toHexString(locationMap.get(memLocation)).getBytes()[0]; //0x00
    result[5] = Integer.toHexString(commandMap.get(commandName) + dataIdMap.get(dataId) + locationMap.get(memLocation)).getBytes()[0];
    result[6] = END_FRAME.getBytes()[0]; // }
    result[7] = END_FRAME.getBytes()[0]; // }
    result[8] = END_OF_LINE.getBytes()[0]; // \r
    return result;
}

对于此函数,某些情况如result[2]存储0xD2,字节值为[100,23] ...值不会按预期出现然后...只有第一个一半被采取......我该如何处理这种情况? result[0]只有[123],它很好......

2 个答案:

答案 0 :(得分:3)

你知道String.getBytes()甚至做什么吗?说实话,这段代码看起来像你不知道,或者你希望它做的事情不是。

它将String对象转换为平台默认编码中的byte[]。在位置byte上取0只会告诉你如何在平台默认编码中表示第一个字符(如果它是单字节编码,否则它会告诉你更少)。

你想要达到什么目的?您还可以使用Integer.toHexString()。您能否举例说明在进行Integer.toHexString(100).getBytes()[0]时您想要的结果完全

答案 1 :(得分:0)

要将字符串“0xD0”转换为字节,我建议您使用Integer.decode(String).byteValue()来处理Java样式00x数字/

我建议您尝试类似

的内容
byte[] result = { 
     '{',
     '{', 
     commandMap.get(commandName), 
     dataIdMap.get(dataId), 
     locationMap.get(memLocation), 
     (byte) (commandMap.get(commandName) + dataIdMap.get(dataId) + locationMap.get(memLocation)), 
     '}', 
     '}', 
     '\r' };
return result;

我会将commandMap等更改为Map< String,Byte>

类型

编辑:这是一个较长的例子

String commandName = "";
String dataId = "";
String memLocation= "";
Map<String, Byte> commandMap = new LinkedHashMap<String, Byte>();
commandMap.put(commandName, Integer.decode("0xD2").byteValue());
Map<String, Byte> dataIdMap = new LinkedHashMap<String, Byte>();
dataIdMap.put(dataId, Integer.decode("0x1").byteValue());
Map<String, Byte> locationMap = new LinkedHashMap<String, Byte>();
locationMap.put(memLocation, Integer.decode("0x00").byteValue());

byte[] result = { '{', '{', commandMap.get(commandName), dataIdMap.get(dataId), locationMap.get(memLocation), (byte) (commandMap.get(commandName) + dataIdMap.get(dataId) + locationMap.get(memLocation)), '}', '}', '\r' };

System.out.println(Arrays.toString(result));

打印

[123, 123, -46, 1, 0, -45, 125, 125, 13]