加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

从char []字节获取int

发布时间:2020-12-16 09:40:19 所属栏目:百科 来源:网络整理
导读:我有一个文件,我读入一个char数组. char数组现在拥有一定数量的字节,现在如果我知道文件存储了一个32位整数的小端,位于0x8位置,我如何从char数组中检索它? FILE * file = fopen("file");char buffer[size];fread(buffer,1,size,file);int = buffer[0x8]; //
我有一个文件,我读入一个char数组.

char数组现在拥有一定数量的字节,现在如果我知道文件存储了一个32位整数的小端,位于0x8位置,我如何从char数组中检索它?

FILE * file = fopen("file");
char buffer[size];
fread(buffer,1,size,file);
int = buffer[0x8]; // What should I do here?
// I imagine it involves some strange pointer
// arithmetic but I can't see what I should do,// casting to int just takes the first byte,// casting to (int *) doesn't compile

解决方法

你需要像这样抛出它:

int foo = *((int *) &buffer[0x8]);

这将首先将该点转换为int指针并将其解除引用到int本身.

[注意不同机器类型的字节顺序;有些人做高字节先有些做低

只是为了确保这个例子很好理解,这里有一些显示结果的代码:

#include <stdio.h>

main() {
    char buffer[14] = { 0,2,3,4,5,6,7,8,9,10,11,12,13 };
    int foo = *((int *) &buffer[0x8]);
    int bar = (int) buffer[0x8];

    printf("raw: %dn",buffer[8]);
    printf("foo: %dn",foo);
    printf("bar: %dn",bar);
}

运行它的结果:

raw: 8
foo: 185207048
bar: 8

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读