将二进制读取函数从C++转换为C#
Converting binary reading function from C++ to C#
老实说,我在阅读C#中的二进制文件时真的很困惑。我有用于读取二进制文件的C++代码:
FILE *pFile = fopen(filename, "rb");
uint n = 1024;
uint readC = 0;
do {
short* pChunk = new short[n];
readC = fread(pChunk, sizeof (short), n, pFile);
} while (readC > 0);
它读取以下数据:
-156, -154, -116, -69, -42, -36, -42, -41, -89, -178, -243, -276, -306,...
我尝试将此代码转换为C#,但无法读取此类数据。这是代码:
using (var reader = new BinaryReader(File.Open(filename, FileMode.Open)))
{
sbyte[] buffer = new sbyte[1024];
for (int i = 0; i < 1024; i++)
{
buffer[i] = reader.ReadSByte();
}
}
我得到以下数据:
100, -1, 102, -1, -116, -1, -69, -1, -42, -1, -36
如何获取类似的数据?
short不是有符号的字节,而是有符号的16位值。
short[] buffer = new short[1024];
for (int i = 0; i < 1024; i++) {
buffer[i] = reader.ReadInt16();
}
这是因为在C++中读取short,而在C#中读取有符号字节(这就是SByte的含义)。您应该使用reader.ReadInt16()
您的C++代码每次读取2个字节(您使用的是sizeof(short)),而您的C#代码每次读取一个字节。SByte(请参阅http://msdn.microsoft.com/en-us/library/d86he86x(v=vs.71).aspx)使用8位存储空间。
您应该使用相同的数据类型来获得正确的输出或转换为新类型。
在c++中,您使用的是short
。(我假设该文件也是用short
编写的),所以在c#中使用short
本身。也可以使用Sytem.Int16
。
由于short
和sbyte
不相等,您得到的值不同。short
是2字节,Sbyte
是1字节
using (var reader = new BinaryReader(File.Open(filename, FileMode.Open)))
{
System.Int16[] buffer = new System.Int16[1024];
for (int i = 0; i < 1024; i++)
{
buffer[i] = reader.ReadInt16();
}
}
相关文章:
- 防止主数据类型C++的隐式转换
- 模板参数替换失败,并且未完成隐式转换
- 努力将整数转换为链表。不知道我在这里做错了什么
- HEX值到wchar_t字符(UTF-8)的转换
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将 Qvector<uint8_t> 转换为 QString
- 如何在cuSparse中使用cusparseXcoo2csr从coo转换为csc
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 在c++中使用nlohmann从类到json的转换
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 如何使用OpenCV将RBG图像转换为HSV,并将H、S和V值保存为C++中的3个独立图像
- 复制列表初始化的隐式转换的等级是多少
- 正在将指针转换为范围
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 将"打开的CV图像"中的"颜色"转换为整数格式
- 是否可以从int转换为enum类类型
- 了解 GLM- openGL 中的相机转换
- 将无符号char*转换为std::istream*C++