c/c++语言开发共享从char 字节获取int

我有一个文件,我读入一个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  main() { char buffer[14] = { 0,1,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 

    假设数组包含与您的机器具有相同字节序的字节,并且没有任何特殊的对齐要求,那么“简单”的方法是:

     int x = *(int *)&buffer[8]; 

    如果你确实有字节序差异,你需要处理它。 如果存在对齐问题(甚至可能存在对齐问题),则应逐个提取字节:

     int x = buffer[8] + (buffer[9] << 8) + (buffer[10] << 16) + (buffer[11] << 24); 

    或者可能是另一个方向,如果字节顺序是另一种方式。

    通过更改该值的两个字(16位)来完成4字节值的Endianess转换,因此效率较低但可读的方式(如果数据是大端编码):

     int val = 0x00000000; char* ptr = reinterpret_cast(&val); *ptr = buffer[0x0a]; ptr++; *ptr = buffer[0x0b]; ptr++; *ptr = buffer[0x08]; ptr++; *ptr = buffer[0x09]; ptr++; 

    但是还有很多其他的方法可以像结构,memcpy那样做…取决于你的目标是什么(性能,可读性……)

    最好的问候,Alex

     int *list = (int*)buffer; int n = fread(buffer, 1, size, file); for (int i=0; i< n/sizeof(int); i++) printf("%dn", list[i]); 

      以上就是c/c++开发分享从char 字节获取int相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/541941.html

      (0)
      上一篇 2021年1月5日
      下一篇 2021年1月5日

      精彩推荐