简体   繁体   English

C:将unsigned char数组转换为signed int(反之亦然)

[英]C: Converting unsigned char array to signed int (vice versa)

I'm trying to convert an unsigned char array buffer into a signed int (vice versa). 我正在尝试将unsigned char数组缓冲区转换为signed int(反之亦然)。

Below is a demo code: 以下是演示代码:

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) Which method should I use to get from unsigned char[] to int? 1)我应该使用哪种方法从unsigned char []到int?

method 1 get or method 2 get? 方法1得到或方法2得到? (or any suggestion) (或任何建议)

2) How do I convert the int original into an unsigned char[]? 2)如何将int原始转换为unsigned char []?

I need to send this integer via a buffer that only accepts unsigned char[] 我需要通过只接受unsigned char []的缓冲区发送这个整数

Currently what i'm doing is converting the int to unsigned int then to char[], example : 目前我正在做的是将int转换为unsigned int然后转换为char [],例如:

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. PS。 I'm trying to send data between 2 devices via USB serial communication (between Raspberry Pi & Arduino) 我正在尝试通过USB串行通信在两个设备之间发送数据(在Raspberry Pi和Arduino之间)

Below approach will work regardless of endianness on machines (assuming sizeof(int)==4 ): 无论机器上的字节顺序如何,下面的方法都可以工作(假设sizeof(int)==4 ):

unsigned char bytes[4];
unsigned int n = 45;

bytes[3] = (n >> 24) & 0xFF;
bytes[2] = (n >> 16) & 0xFF;
bytes[3] = (n >> 8) & 0xFF;
bytes[0] = n & 0xFF;

Above code converts integer to byte array in little endian way. 上面的代码以little endian方式将整数转换为字节数组。 Here is link also with more information. 这里是链接还有更多信息。

For reverse operation, see the answers here . 有关反向操作,请参阅此处的答案。

The approach you have with memcpy may give different results on different computers. 使用memcpy的方法可能会在不同的计算机上提供不同的结果。 Because memcpy will copy whatever is there in source address to destionation, and depending if computer is little endian or big endian, there maybe a LSB or MSB at the starting source address. 因为memcpy会将源地址中的任何内容复制到destionation,并且根据计算机是小端还是大端,可能在起始源地址处有一个LSB​​或MSB。

You could store both int (or unsigned int ) and unsigned char array as union . 您可以将int (或unsigned int )和unsigned char数组存储为union This method is called type punning and it is fully sanitized by standard since C99 (it was common practice earlier, though). 这种方法称为类型惩罚,并且自C99以来它被标准完全消毒(尽管之前是常见的做法)。 Assuming that sizeof(int) == 4 : 假设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 , ie endianess. 请注意,由于字节顺序 (即字节顺序) ,存储数组中的值。

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

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