我在许多与此相关的线程中都没有找到任何解决方案。我的确切问题是:
我有一个整数数组,例如unsigned int arr[2] = {0xFEBD1213, 0x1213FEBD};
我想逐字符访问那些整数char,这意味着我需要阅读:0x13, 0x12, 0xBD, 0xFE, 0xBD, 0xFE, 0x13, 0x12
。我尝试了许多很多事情,但没有成功。
注意:我也想做相反的事情:拥有一个大小为
size %4 == 0
的char数组,并将其读取为整数数组。例如: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++);
}
}
((我知道有很多更简洁的方法可以对此进行编码,但是我无法控制给定数组的类型)
一个简单的移位并且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
要从字节到数组,只需向相反的方向移动或”。
#include <stdio.h>
#include <stdlib.h>
void main(void){
unsigned int arr[2] = {0xFEBD1213, 0x1213FEBD};
unsigned char * ptr;
ptr = &arr;
for(int i = 0; i < 2 * 4; i++){
printf("%x\n", *ptr);
ptr = &*(ptr)+1;
}
unsigned char arr_c[8] = {0x13, 0x12, 0xBD, 0xFE, 0xBD, 0xFE, 0x13, 0x12};
unsigned int * ptr_i;
ptr_i = &arr_c;
for(int i = 0; i < 2; i++){
printf("%x\n", *ptr_i);
ptr_i = &*(ptr_i)+1;
}
}
您可以使用某种解析器: