从字节的char []中获取int [英] Get int from char[] of bytes
问题描述
我有一个读入char数组的文件.
I have a file that I read into a char array.
char数组现在拥有一定数量的字节,如果我知道文件在小字节序存储的0x8位置存储了一个32位整数,该如何从char数组中检索它?
The char array now holds a certain number of bytes, now if I know the file stored a 32bit integer in little endian at position say 0x8, how do I retrieve it from the char array?
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
推荐答案
您需要像这样进行投射:
you need to cast it like so:
int foo = *((int *) &buffer[0x8]);
首先将点转换为int指针,然后将其取消引用为int本身.
Which will first cast the spot to a int pointer and the dereference it to the int itself.
[但是要注意不同机器类型之间的字节顺序;有些先做高字节,有些先做低字节]
[watch out for byte-ordering across different machine types though; some do high bytes first some do low]
为了确保示例易于理解,下面的代码显示了结果:
And just to make sure the example is well understood, here's some code showing the results:
#include <stdio.h>
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: %d\n", buffer[8]);
printf("foo: %d\n", foo);
printf("bar: %d\n", bar);
}
运行结果以及
raw: 8
foo: 185207048
bar: 8
这篇关于从字节的char []中获取int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!