Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何从C++;?_C++_C_Binary_Binaryfiles - Fatal编程技术网

C++ 如何从C++;?

C++ 如何从C++;?,c++,c,binary,binaryfiles,C++,C,Binary,Binaryfiles,假设我有一个二进制文件;它包含正二进制数,但以32位整数的小尾数形式写入 如何读取此文件?我现在有这个 int main() { FILE * fp; char buffer[4]; int num = 0; fp=fopen("file.txt","rb"); while ( fread(&buffer, 1, 4,fp) != 0) { // I think buffer should be 32 bit integer I

假设我有一个二进制文件;它包含正二进制数,但以32位整数的小尾数形式写入

如何读取此文件?我现在有这个

int main() {
    FILE * fp;
    char buffer[4];
    int num = 0;
    fp=fopen("file.txt","rb");
    while ( fread(&buffer, 1, 4,fp) != 0) {

        // I think buffer should be 32 bit integer I read,
        // how can I let num equal to 32 bit little endian integer?
    }
    // Say I just want to get the sum of all these binary little endian integers,
    // is there an another way to make read and get sum faster since it's all 
    // binary, shouldnt it be faster if i just add in binary? not sure..
    return 0;
}
发件人:


这是一种适用于大端或小端体系结构的方法:

int main() {
    unsigned char bytes[4];
    int sum = 0;
    FILE *fp=fopen("file.txt","rb");
    while ( fread(bytes, 4, 1,fp) != 0) {
        sum += bytes[0] | (bytes[1]<<8) | (bytes[2]<<16) | (bytes[3]<<24);
    }
    return 0;
}
intmain(){
无符号字符字节[4];
整数和=0;
FILE*fp=fopen(“FILE.txt”、“rb”);
while(fread(字节,4,1,fp)!=0){

sum+=bytes[0]|(bytes[1]如果您使用的是linux,您应该查看;-)


这是关于有用的函数,例如le32toh

可能重复的@OmnipotentEntity:这个问题涉及同一类问题,但我认为是不同的。初学者会发现链接的问题和答案很难理解。如果您使用的是80x86机器-所有这些机器都使用小endian-您不需要做任何修改调整数字。一些答案假设读者也不是小endian。OP没有提到这一点,只是作者使用了LE输出格式。主题代码应该是可移植的,以处理LE或be读者(谢天谢地,有些人是这样的)。这在技术上是未定义的行为。如果您正在读取的数字为负数,则可以通过强制转换
(无符号)字节[3]+1:来避免这种情况,因为不假定读取器为(虽然我在
fread()
)上会使用4,1)@WhozCraig:fread的大小和计数参数的正确点已更改。字节[0]之后是否需要0xFF?如(缓冲区[0]和0xFF)|(缓冲区[1]和0xFF)@user1713700:字节的每个元素只包含一个字节,因为它是无符号的,所以不需要屏蔽高位,因为它们都是零。非常感谢,但另一个答案对我的问题更精确。你能扩展这个链接吗?只回答这个问题吗?添加一些示例代码。我对各种方法进行了计时。linux库函数如le32toh和bswap_32的运行速度比位移位算法快10倍。
while ( fread(&num, 1, 4,fp) != 0) {
    endian_swap(num); 
    // conversion done; then use num
}
int main() {
    unsigned char bytes[4];
    int sum = 0;
    FILE *fp=fopen("file.txt","rb");
    while ( fread(bytes, 4, 1,fp) != 0) {
        sum += bytes[0] | (bytes[1]<<8) | (bytes[2]<<16) | (bytes[3]<<24);
    }
    return 0;
}