c - 以 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++);
}
}
(我知道有很多更简洁的编码方式,但我无法控制给定数组的类型)
解决方案
一个简单的转变和 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。
推荐阅读
- python - Python:将 csv 文件压缩为 .gz 会引发错误
- ggplot2 - 查看警告消息中的行
- mysql - 存储过程 - 一行选择语句语法错误
- gnu-findutils - 为什么 find 将正则表达式应用于完整路径名?
- android - 从 Fragment 调用 viewHolder 方法
- pandas - 在相似的字符串上加入 2 个表
- dropbox-api - 使用 Dropzone 通过 upload_sessions 将文件上传到 Dropbox
- xslt - 使用 XSLT 1、2 或 3 根据两个元素的组合文本识别文件中的重复条目
- python - TypeError:“Styler”对象不可下标
- apache-kafka - 如何通知特定服务的扩展实例有关数据库的更改?