繁体   English   中英

如何将大整数转换为字节

[英]How to convert a large integer to bytes

我需要通过串行通信将值115200作为参数发送到外部设备,该设备需要将该参数作为字节数组的一部分,格式为: 0x00, 0x00, 0x00, 0x00我不知道如何将其转换为该格式。 我正在处理中执行此操作,因此处理/ 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位(byte [4]-byte [7])。

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

0 0x55 BYTE命令开始代码1

1 0xAA BYTE命令开始代码2

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

4参数DWORD输入参数

8命令字命令代码

10校验和WORD校验和(字节累加)OFFSET [0] +…+ OFFSET [9] =校验和

任何建议将不胜感激。 谢谢

您尝试将一个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类的int_to_bytes和类似的函数非常方便,这些函数以通用的方式进行操作,从而减少了代码的混乱度。

假定字节为小尾数格式,则应将它们设置如下:

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。

你需要掩盖和转移

int num = 115200
int b1 = (num & 0xff000000) >> 24
int b2 = (num & 0x00ff0000) >> 16
int b3 = (num & 0x0000ff00) >> 8
int b4 = (num & 0x000000ff) >> 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);

暂无
暂无

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

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