如何从char [4]创建int?(在C中)

use*_*456 2 c casting

我有char [4]并且在其中: a[0] = 0x76 a[1] = 0x58 a[2] = 0x02 a[3] = 0x00 我想打印它int,你能告诉我该怎么做吗?

Eri*_*man 7

这可行,但根据int,endian等的大小给出不同的结果.

#include <stdio.h>

int main(int argc, char *argv[])
{

    char a[4];
    a[0] = 0x76;
    a[1] = 0x58;
    a[2] = 0x02;
    a[3] = 0x00;
    printf("%d\n", *((int*)a));
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是更干净,但你仍然有端/大小的问题.

#include <stdio.h>

typedef union {
    char c[4];
    int i;
} raw_int;

int main(int argc, char *argv[])
{

    raw_int i;
    i.c[0] = 0x76;
    i.c[1] = 0x58;
    i.c[2] = 0x02;
    i.c[3] = 0x00;
    printf("%d\n", i.i);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

要强制使用某个字节序,请int手动构建:

int i = (0x00 << 24) | (0x02 <<< 16) | (0x58 << 8) | (0x76);
printf("%d\n", i);
Run Code Online (Sandbox Code Playgroud)


Mac*_*ack 5

我认为工会是这样做的合适方式。

#include <stdio.h>
#include <stdint.h>

union char_int {
    char chars[4];
    int32_t num;
};

int main() {
    union char_int tmp;

    tmp.chars[0] = 0x76;
    tmp.chars[1] = 0x58;
    tmp.chars[2] = 0x02;
    tmp.chars[3] = 0x00;
    printf("%d\n", tmp.num);
}
Run Code Online (Sandbox Code Playgroud)