首页 > 解决方案 > 以 int 数组的形式访问和读取 char 数组

问题描述

在有关此的许多线程中,我没有找到任何解决方案。我的确切问题是:

我有一个整数数组,例如unsigned int arr[2] = {0xFEBD1213, 0x1213FEBD};

我想逐个字符地访问这些整数,这意味着我需要阅读 : 0x13, 0x12, 0xBD, 0xFE, 0xBD, 0xFE, 0x13, 0x12。我尝试了很多很多东西,但我还没有成功。

注意:我也想做相反的事情:拥有一个大小为 的 char 数组size %4 == 0,并将其作为整数数组读取。例如:unsigned char arr[8] = {0x13, 0x12, 0xBD, 0xFE, 0xBD, 0xFE, 0x13, 0x12}并阅读0xFEBD1213, 0x1213FEBD

有没有办法做这样的事情?

最小的可重现示例:

#include <stdio.h>
#include <stdlib.h>
void main(void){
  unsigned int arr[2] = {0xFEBD1213, 0x1213FEBD};
  unsigned char * ptr;
  ptr = *&arr; // I need a variable. Printing it doesn't matter to me. I am aware that there are easy solutions to print the right values there.
  for(int i = 0; i < 2 * 4; i++){
    printf("%x\n", *ptr);
    ptr = (ptr++);
  }
}

(我知道有很多更简洁的编码方式,但我无法控制给定数组的类型)

标签: cpointersmemory

解决方案


一个简单的转变和 AND 将起作用:

#include <stdio.h>
#include <limits.h>

int main (void) {

    unsigned int arr[2] = {0xFEBD1213, 0x1213FEBD};

    for (size_t i = 0; i < 2; i++)
        for (size_t j = 0; j< sizeof *arr; j++)
            printf ("0x%hhx\n", arr[i] >> (j * CHAR_BIT) & 0xff);
}

示例使用/输出

$ ./bin/arrbytes
0x13
0x12
0xbd
0xfe
0xbd
0xfe
0x13
0x12

要从字节到数组,只需移动相反的方向和 OR。


推荐阅读