如何将大整数转换为字节

时间:2015-11-05 17:06:45

标签: java c type-conversion bytearray processing

我需要将值115200作为参数通过串行通信发送到外部设备,该外部设备要求参数作为字节数组的一部分,格式为:0x00, 0x00, 0x00, 0x00,我不知道如何将其转换为该格式。 我在Processing中这样做,所以Processing / java解决方案将来会很方便,但ATM我很高兴,如果我可以发送带有这个特定变量的消息。

这是字节数组:

byte[] tx_cmd = { 0x55, -86,             // packet header (-86 == 0xAA) 
                0x01, 0x00,              // device ID
                0x00, 0x00, 0x00, 0x00,  // input parameter NEEDS TO BE 115200
                0x04, 0x00,              // command code
                0x00, 0x01 };            // checksum

参数需要放在第5位到第8位(字节[4] - 字节[7])。

消息格式是小端,这是消息结构:

0 0x55 BYTE命令启动代码1

1 0xAA BYTE命令启动代码2

2设备ID WORD设备ID:默认为0x0001,始终固定

4参数DWORD输入参数

8命令WORD命令代码

10检查Sum WORD 校验和(字节添加) OFFSET [0] + ... + OFFSET [9] =校验和

非常感谢任何建议。 谢谢

4 个答案:

答案 0 :(得分:1)

你试图将打包一个int转换成字节,你没有提到它是否是网络顺序,所以我们假设它是(例如第一个字节,tx_cmd [4],是最高的数字的字节):

unsigned int baudrate = 115200;
tx_cmd[4] = (baudrate >> 24) & 0xff;
tx_cmd[5] = (baudrate >> 16) & 0xff;
tx_cmd[6] = (baudrate >> 8) & 0xff;
tx_cmd[7] = baudrate & 0xff;

一般来说,使用像int_to_bytes这样的函数非常方便,这些函数以通用的方式执行,并使代码更简洁。

答案 1 :(得分:1)

如果字节预期为小端格式,您可以按如下方式设置它们:

uint32_t value = 115200;
tx_cmd[4] = value & 0xff;
tx_cmd[5] = (value >> 8) & 0xff;
tx_cmd[6] = (value >> 16) & 0xff;
tx_cmd[7] = (value >> 24) & 0xff;

重要的是你正在使用的值是无符号的,否则如果设置了最高有效位,你就有可能将1移入。

答案 2 :(得分:0)

你需要掩饰和转移

int num = 115200
int b1 = (num & 0xff000000) >> 24
int b2 = (num & 0x00ff0000) >> 16
int b3 = (num & 0x0000ff00) >> 8
int b4 = (num & 0x000000ff) >> 0

答案 3 :(得分:0)

建议创建一个包装所有内容的功能

#define byte_n(x, b) ((x >> (b*8)) & 0xFF)

void CreatePacket(byte tx_cmd[], uint16_t device_id, uint32_t param, uint16_t command) {
  #define HEADER 0xAA55
  tx_cmd[0] = byte_n(HEADER, 0);
  tx_cmd[1] = byte_n(HEADER, 1);
  tx_cmd[2] = byte_n(device_id, 0);
  tx_cmd[3] = byte_n(device_id, 1);
  tx_cmd[4] = byte_n(param, 0);
  tx_cmd[5] = byte_n(param, 1);
  tx_cmd[6] = byte_n(param, 2);
  tx_cmd[7] = byte_n(param, 3);
  tx_cmd[8] = byte_n(command, 0);
  tx_cmd[9] = byte_n(command, 1);
  unsigned checksum = 0;
  for (int i=0; i<10; i++) {
    checksum += tx_cmd[i];
  }
  tx_cmd[10] = byte_n(checksum, 0);
  tx_cmd[11] = byte_n(checksum, 1);
}

byte tx_cmd[12];
device_id = 1;
baud = 115200;
command = 4;
CreatePacket(tx_cmd, device_id,  baud, command);
相关问题