[英]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.