【发布时间】:2021-09-20 05:59:33
【问题描述】:
我想在 C++ 中以二进制模式读取文件。最初,当我使用 python 读取相同的文件时,我使用 python 来做同样的事情,我得到了结果b'\xe0\xa4\xb5\xe0\xa4\xbe\xe0\xa4\xb9',当转换为 INT 时,结果为224 164 181 224 164 190 224 164 185,我能够注意到所有这些 INT 始终在范围内 @ 987654324@.
我想在 c++ 中做同样的事情,但我无法做同样的事情我尝试了很多不同的技巧,但我能得到的最好的方法是 c++ 给出负整数。
#include <iostream>
#include <io.h>
#include <fcntl.h>
#include <fstream>
#include <stdio.h>
int main()
{
std::fstream file("a.txt", std::ios::out | std::ios::in | std::ios::binary);
file.seekg(0, std::ios::end);
int size = file.tellg();
char ch;
std::string text;
std::cout << "Size = " << size << std::endl;
file.seekg(0, std::ios::beg);
char x;
file.read((&x), 1);
std::cout << static_cast<int>(x) << std::endl;
return 0;
}
请忽略#include,我已经使用了很多。
OUTPUT
Size = 9
-32
【问题讨论】:
-
打印时将值转换为
unsigned int。 -
嘿,但这会导致
4294967264作为输出,但正如我所说,我想读取文件,以便我得到[0,255]范围内的 INT,你能建议任何方法吗 -
停止阅读
chars。他们经常签名。请改用unsigned char或<cstdint>的uint8_t。std::byte如果你有的话。 -
-32 与 224 的位模式相同。只是取决于您如何可视化它。 `ideone.com/hvekS6
-
当您使用
char时,它会将其视为signed char,其值在[-128, 127]范围内,然后224表示-32
标签: python c++ file stream binary