简体   繁体   English

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

[英]How to make int from char[4]? (in C)

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

This works, but gives different results depending on the size of int, endian and so on.. 这可行,但根据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;
}

This is cleaner but you still have endian/size problems. 这是更干净,但你仍然有端/大小的问题。

#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;
}

To force a certain endianness, build the int manually: 要强制使用某个字节序,请手动构建int

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

I think a union is the appropriate way to do this. 我认为工会是这样做的合适方式。

#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);
}

Other option can be using bitwise operators | 其他选项可以使用按位运算符| and << left shift, as follows (to understand read comments): <<左移,如下(了解阅读评论):

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

  char a[4];
  int32_t  i = 0;  // 32 bits = 4 bytes
  a[0] = 0x76;
  a[1] = 0x58;
  a[2] = 0x02;
  a[3] = 0x00;

  i = 0;   // initial  value must be `0`
  i = i | a[0] << ( 3 * 8); // 0x76 => 0x76 00 00 00, gives i = 0x76 00 00 00  
  i = i | a[1] << ( 2 * 8); // 0x58 => 0x00 58 00 00, gives i = 0x76 58 00 00
  i = i | a[2] << ( 1 * 8); // 0x02 => 0x00 00 02 00, gives i = 0x76 58 02 00
  i = i | a[3] << ( 0 * 8); // 0x02 => 0x02   
                            //      => 0x00 00 00 02, gives i = 0x76 58 02 00 

  printf("Hex: %x\nDec: %d \n", i, i);
  return 0;
}

ouput: 输出继电器:

$ gcc  -Wall -pedantic yy.c 
$ ./a.out 
Hex: 76580200            <- "hex decimal"
Dec: 1985479168          <- "decimal"

Notice: i = i | a[3] << ( 0 * 8); 注意: i = i | a[3] << ( 0 * 8); i = i | a[3] << ( 0 * 8); can be just i = i | a[3]; 可以只是i = i | a[3]; i = i | a[3]; , I written like that to keep code uniform. ,我这样写,以保持代码统一。

Edit: 编辑:

Oh you can just do it like: 哦,你可以这样做:

i = 0 | 
     a[0] << ( 3 * 8) | 
     a[1] << ( 2 * 8) |
     a[2] << ( 1 * 8) |
     a[3] << ( 0 * 8);

Look here: Codepade for working code. 看看这里: Codepade的工作代码。

Is the value stored in the array in big-endian or little-endian order? 值是以big-endian还是little-endian顺序存储在数组中的? The portable way to do it is based on shift and mask, noting that in the general case, some of the high-order bits will be set and your plain char type might be signed or unsigned. 可移植的方法是基于移位和掩码,注意在一般情况下,将设置一些高位,并且您的普通char类型可能是有符号或无符号的。

Little-endian 小端

int i = (a[3] << 24) | ((a[2] & 0xFF) << 16) | ((a[1] & 0xFF) << 8) | (a[0] & 0xFF);

Big-endian 大端

int i = (a[0] << 24) | ((a[1] & 0xFF) << 16) | ((a[2] & 0xFF) << 8) | (a[3] & 0xFF);

You can change those so that each term is consistently of the form ((a[n] & 0xFF) << m) . 您可以更改这些,以便每个术语始终具有形式((a[n] & 0xFF) << m) If you know that plain char is unsigned, you can drop the mask operations. 如果您知道plain char是无符号的,则可以删除掩码操作。 You can also use a cast: unsigned char *u = (unsigned char *)a; 你也可以使用强制转换: unsigned char *u = (unsigned char *)a; and then dereference u instead of a . 然后取消引用u而不是a

If you want to read it as a big- or little-endian integer, just do some bit shifting: 如果你想把它读成大端或小端整数,只需做一些位移:

char a[4] = {0x76, 0x58, 0x02, 0x00};

// Big-endian:
uint32_t x = ((uint8_t)a[0] << 24) | ((uint8_t)a[1] << 16) | ((uint8_t)a[2] << 8) | (uint8_t)a[3];

// Little-endian:
uint32_t y = (uint8_t)a[0] | ((uint8_t)a[1] << 8) | ((uint8_t)a[2] << 16) | ((uint8_t)a[3] << 24);

If you want to read it as a native-endian integer, you can either cast the array to a pointer to an integer and dereference that. 如果要将其作为native-endian整数读取,可以将数组转换为指向整数的指针并取消引用。 Note that the former is allowed only for char arrays -- for any other types, doing so breaks C's strict aliasing rules, so that would not be safe or portable. 请注意,前者允许char数组-这是任何其他类型的,这样做打破了C'S严格别名规则,所以这不会是安全的或便携式的。 For example: 例如:

char a[4] = {0x76, 0x58, 0x02, 0x00};

// Cast to pointer to integer and dereference.  This is only allowed if `a' is an
// array of `char'.
uint32_t x = *(uint32_t *)a;

Alternatively, you can use a union, or just memcpy() the data directly. 或者,您可以直接使用union,或者只使用memcpy()数据。 Both of these are safe and portable, as long as a char is 8 bits (its size in bits is given by the macro CHAR_BIT ). 这两个都是安全和可移植的,只要char是8位(其大小以位为单位由宏CHAR_BIT给出)。

char a[4] = {0x76, 0x58, 0x02, 0x00};
uint32_t x;

// Copy the data directly into x
memcpy(&x, a, sizeof(x));

// Use a union to perform the cast
union
{
    char a[4];
    uint32_t x;
} u;
memcpy(u.a, a, sizeof(a));
// u.x now contains the integer value

Note that I've used uint32_t in all of the examples above, since an int is not guaranteed to be 4 bytes on all systems. 请注意,我在上面的所有示例中都使用了uint32_t ,因为在所有系统上都不保证int为4个字节。 The type uint32_t is defined in the header file <stdint.h> , and if it's defined by your compiler, it's guaranteed to be 32 bits wide. uint32_t类型在头文件<stdint.h>定义,如果它由编译器定义,则保证为32位宽。

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

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