如何在C++中将二进制文件上下文转换为 int/long 值
How to convert binary files context into int/long value in C++
我正在使用fstream将值存储在二进制文件中。该值为无符号短类型。
unsigned shord value=1750; //2 byte variable
file.write((char*)&value,sizeof(value));
我的问题是我想在另一个函数中读取这个二进制文件,但它给了我一些奇怪的符号(显然是因为它是二进制的)。
有没有办法获取这两个字节并将它们转换为我的旧值 (1750) ?
这是我尝试过的:
cout <<(unsigned short)(unsigned char)(s2[8]);//s2 variable where the whole body is stored
cout <<(unsigned short)(char*)(s2[8]);
我也尝试过其他东西,但它们只是鸡抓,不值得包括在这里。
以下是您可以操作的方法(注意使用 C++11 个功能):
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
void write_shorts(string filename, vector<unsigned short> shorts)
{
ofstream f;
f.open(filename, ofstream::trunc|ofstream::binary);
for(auto s: shorts)
f.write(reinterpret_cast<char*>(&s), sizeof(s));
}
auto read_shorts(string filename)
{
ifstream f(filename);
vector<unsigned short> res;
short x;
while(f.read(reinterpret_cast<char*>(&x), sizeof(x)))
res.push_back(x);
return res;
}
int main()
{
// Write 3 shorts to a file
write_shorts("myshorts", {4711, 1, 0xffff});
// Read them back into a vector
auto v = read_shorts("myshorts");
cout << "Read " << v.size() << "shorts: " << endl;
for(auto x: v)
cout << x << endl;
}
相关文章:
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 是否可以从int转换为enum类类型
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 功能样式转换从 'int' 到 'ItemType' 的匹配转换
- 将 int 数组转换为 std::vector<int*>
- 如何转换 int 变量并附加到常量 wchar_t*
- 类型转换<int>的舍入问题
- 在Objective-C中调用sqlite3数据库时,如何调用和转换int/NSNumber
- 转换 int -> 无符号长 长 是否由标准定义
- 简单的 int 到字符串转换..int to const char* 无效
- 如何将转换 int 除法键入为浮点数
- C++类型转换 int * 到类
- 预期的类型说明符,并且无法在初始化时转换“int*”
- 转换int并将其与char*连接
- 字符串流在转换int型时添加新行
- 转换int为字符串/char c++ /Arduino
- c# P-Invoke:如何转换INT fun(BYTE *bStream, UINT16 *nCount, const
- 类型转换(int**)和int(*)的区别
- 从"int"到"nodeType"的无效转换<int>
- 从无符号int构造对强制转换int的引用