C:将无符号字符数组转换为带符号的int(反之亦然)
我正在尝试将无符号的char数组缓冲区转换为带符号的int(反之亦然).
I'm trying to convert an unsigned char array buffer into a signed int (vice versa).
下面是一个演示代码:
int main(int argv, char* argc[])
{
int original = 1054;
unsigned int i = 1054;
unsigned char c[4];
int num;
memcpy(c, (char*)&i, sizeof(int));
//num = *(int*) c; // method 1 get
memcpy((char *)&num, c, sizeof(int)); // method 2 get
printf("%d\n", num);
return 0;
}
1)我应该使用哪种方法将unsigned char []转换为int?
方法1获取或方法2获取? (或任何建议)
method 1 get or method 2 get? (or any suggestion)
2)如何将int原件转换为未签名的char []?
我需要通过一个仅接受无符号char []的缓冲区发送该整数
I need to send this integer via a buffer that only accepts unsigned char[]
当前我正在做的是将int转换为unsigned int,然后转换为char [],例如:
Currently what i'm doing is converting the int to unsigned int then to char[], example :
int g = 1054;
unsigned char buf[4];
unsigned int n;
n = g;
memcpy(buf, (char*)&n, sizeof(int));
虽然可以正常工作,但我不确定它的正确方法还是安全?
Although it works fine but i'm not sure if its the correct way or is it safe?
PS.我正在尝试通过USB串行通信(在Raspberry Pi和Arduino之间)在2个设备之间发送数据
PS. I'm trying to send data between 2 devices via USB serial communication (between Raspberry Pi & Arduino)
您可以将int
(或unsigned int
)和unsigned char
数组都存储为union
.此方法称为键入punning ,并且自C99以来,它已完全通过标准进行了清理(这很常见尽早练习).假设sizeof(int) == 4
:
You could store both int
(or unsigned int
) and unsigned char
array as union
. This method is called type punning and it is fully sanitized by standard since C99 (it was common practice earlier, though). Assuming that sizeof(int) == 4
:
#include <stdio.h>
union device_buffer {
int i;
unsigned char c[4];
};
int main(int argv, char* argc[])
{
int original = 1054;
union device_buffer db;
db.i = original;
for (int i = 0; i < 4; i++) {
printf("c[i] = 0x%x\n", db.c[i]);
}
}
请注意,由于字节顺序(即字节顺序)而存储数组中的值.
Note that values in array are stored due to byte order, i.e. endianess.