将十六进制数组(char *)转换为整数
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将十六进制数组(char *)转换为整数相关的知识,希望对你有一定的参考价值。
我需要将字节转换为C中的int(或uint8 / 16/32)。这是我的代码的解释:
char* out;
//init
//out=read_udp (from equipment)
for(int i=0; i<n; ++i)
printf("out[%d]=%x ", i, out[i]);
输出:
out [0] = 0x00 out [1] = 0xAA out [2] = 0x44 out [3] = 0x12 out [4] = 0x2B out [5] = 0x00 out [6] = 0x7E out [7] = 0x3B
前四个字节是标题,后跟一个ID和一个值(每个字节有两个小端字节)。我怎样才能获得ID和价值?
Failed attempts
我试着指向整数:
char* p_ID;
char* p_val;
//malloc
p_ID=&out[4];
p_val=&out[6];
printf("%d %d", p_ID, p_val);
我也试过改变字节顺序
p_ID[0]=out[1]; p_ID[1]=out[2];
我也尝试过sscanf和strol解决方案,但我得到了奇怪的结果。
答案
让我举一个您正在寻找的例子。
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#define SWAP2BYTES(val) (((val>>8)&0x00FF)|((val<<8)&0xFF00))
bool isLittleEndian() { // just to check host endian
uint32_t val = 1;
uint8_t *c = (uint8_t*)&val;
return (1 == (uint32_t)*c);
}
// if the same endian, then no need to swap, otherwise swap
#define CHECKSWAP(val) (isLittleEndian()?val:SWAP2BYTES(val))
int main(int argc, char **argv) {
uint8_t out[8] = {0x00,0xAA,0x44,0x12,0x2B,0x00,0x7E,0x3B};
uint16_t id, val;
// to prevent from alignment issue, memcpy used insted of assignment
memcpy((uint8_t*)&id, &out[4], sizeof(id));
memcpy((uint8_t*)&val, &out[6], sizeof(val));
id = CHECKSWAP(id);
val = CHECKSWAP(val);
printf("outdata = ");
for (int i = 0; i < sizeof(out); i++)
printf("0x%02x ", out[i]);
printf("
");
printf("Header: 0x%02x 0x%02x 0x%02x 0x%02x.
", out[0], out[1], out[2], out[3]);
// just to make sure whether or not intended values are retrieved
printf("ID: %d(0x%04x), Value: %d(0x%04x).
", id, id, val, val);
return 0;
}
在我的电脑上,以下是输出:
outdata = 0x00 0xaa 0x44 0x12 0x2b 0x00 0x7e 0x3b
Header: 0x00 0xaa 0x44 0x12.
ID: 43(0x002b), Value: 15230(0x3b7e).
以上是关于将十六进制数组(char *)转换为整数的主要内容,如果未能解决你的问题,请参考以下文章