简体   繁体   English

在C中将char数组转换为int

[英]Convert char array into int in C

Say you have an char array, which holds 8 bytes. 假设您有一个char数组,其中包含8个字节。 How would you convert that char array into an integer? 您如何将char数组转换为整数?

I tried using sscanf - 我尝试使用sscanf-

int x;
sscanf(char_array, "%d", &x);

I'm reading bytes from a binary file, storing them into a char array, and then I'm trying to print out an int value based on an offset value. 我从二进制文件中读取字节,将其存储到char数组中,然后尝试基于偏移值打印出int值。

The following converts a 4 byte array (4 chars) into a 32-bit unsigned integer. 下面的代码将4字节数组(4个字符)转换为32位无符号整数。 You should be able to easily extend this to 8 chars (ie, 64-bit unsigned int). 您应该能够轻松地将此扩展为8个字符(即64位unsigned int)。

Iterate array backwards (can do forwards as well) and shift the int representation of the respective character accordingly and fit it into the resultant value. 向后迭代数组(也可以向前进行迭代),并相应地移动各个字符的int表示形式,并将其拟合为结果值。

#include <iostream>
#include <cstdint>

using namespace std;

int main() {
    char arr[] = {0x00, 0x00, 0x1B, 0x1B}; // just for my testing convenience
    uint32_t val = 0;
    for (int i = 3; i >= 0; i--) {
        uint32_t tmp = arr[i];
        int j = 4 - i;
        while (--j) {
            tmp <<= 8;
        }
        val |= tmp;
    }

    cout << val << endl;
}

Combining 8 char into an integer would result in a 64-bit integer, so you may need to declare it as unsigned long long int ... 将8个char组合成一个整数将得到一个64位整数,因此您可能需要将其声明为unsigned long long int ...

#include <stdio.h>

void showBinary(unsigned long long x) {
    int i;
    for(i = 63; i >= 0; i--) 
        printf("%d", x & (1ULL << i) ? 1 : 0);
    printf("\n");
}

int main(void) {
    char c[8] = {1, 2, 3, 4, 'a', 'b', 'c', 'd'};
    unsigned long long int x = 0;

    int char_i;
    for (char_i = 0; char_i < 8; char_i++) {
        x = (x << 8) | c[char_i];
        showBinary(x);
    }
    printf("Result: x = %lld\n", x);

    return 0;
}

ps. ps。 When you read bytes from file, you may need to be careful about the big-endian or little-endian representation. 从文件读取字节时,可能需要注意大端或小端表示。

I think you just want to read hexadecimal numbers which are usually 8 bytes in text form. 我认为您只想读取十六进制数字,通常以文本形式为8个字节。 You can use this: 您可以使用此:

sscanf(char_array, "%x", &x);

If it's really binary, it would be 4 bytes each and it depends if the machine is little-endian or big-endian. 如果它是真正的二进制文件,则每个字节为4个字节,这取决于计算机是小端还是大端。 Most computers are little-endian. 大多数计算机都是低端的。 To make a portable version, you can use these functions: 要制作便携式版本,可以使用以下功能:

#ifdef BIG_ENDIAN
#define memcpy_set(buf,v) memcpy(buf, &v, 4)
#else
#define memcpy_set(buf,v) { for (int i = 0; i < 4; i++) buf[i] = v >> (24 - 8 * i); }
#endif
#define memcpy_get(buf) (buf[0] << 24 | buf[1] << 16 | buf[2] << 8 | buf[3])

int main()
{
    if (sizeof(int) != 4)
        return 0;

    char buf[5];
    memset(buf, 0, 5);

    memcpy_set(buf, 0x41424344);
    printf("%s\n", buf);// buf = "ABCD"
    printf("%x\n", memcpy_get(buf)); //0x41424344

    return 0;
}

If you are reading bytes from a binary file, I suggest to read directly from the file to the integer variable. 如果要从二进制文件中读取字节,我建议直接从文件中读取整数变量。 As followed: 如下:

#include        <stdio.h>

int             main() {
  FILE          *file = fopen("myFile", "r");
  int           i;

  if (file) {
    fread(&i, sizeof(i), 1, file);
    printf("%d\n", i);
    fclose(file);
  }
  return (0);
}

But if you cannot get rid of your char array as a source for the conversion, you can use a union to easily perform the conversion: 但是,如果您不能摆脱char数组作为转换源的情况,可以使用并集轻松地执行转换:

#include        <stdio.h>
#include        <string.h>

typedef union           u_bytes_to_int_type
{
  int                   value;
  char                  bytes[sizeof(int)];
}                       u_bytes_to_int_type;

void                    reverseArray(char *array, unsigned int const size) {
  char                  tmp;
  unsigned int          reverseIdx;

  for (unsigned int i = 0; i < size / 2; ++i) {
    reverseIdx = size - 1 - i;

    tmp = array[i];
    array[i] = array[reverseIdx];
    array[reverseIdx] = tmp;
  }
}

int                     main() {
  char                  endiannessIsDifferent = 0; // It's up to you how you determine the value of this variable.
  char                  array[sizeof(int)] = {0x2a, 0, 0, 0};
  u_bytes_to_int_type   v;

  memcpy(v.bytes, array, sizeof(array));
  /*
  ** Will reverse the order of the bytes in case the endianness of
  ** the source array is different from the one you need.
  */
  if (endiannessIsDifferent) {
    reverseArray(v.bytes, sizeof(v.bytes));
  }

  printf("%i\n", v.value);
  return (0);
}

Is it really char array and not unicode where 2 bytes represent one character? 是2个字节代表一个字符的真正的char数组而不是unicode吗? Are you sure result will fit into int? 您确定结果适合int吗? If so, then here is simple solution: 如果是这样,那么这里是一个简单的解决方案:

int x=0;
for (int i=0; i<8; i++) x=x*10 + char_array[i]-'0';

我通常认为您必须先将其存储为字符,然后在println()期间将其转换为int。

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

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