从二进制文件中逐个读取字节
Reading bytes one by one from binary file
这是我的问题,我想打开一个.jpg文件,并将每个字节以逗号分隔的十进制数(0-255)写入另一个.txt文件。现在,它应该能够使用该txt文件再次构建.jpf文件。我就是这么想的。
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
long x;
char *s;
ifstream ifs("image.jpg",ios::binary);
ifs.seekg(0,ios::end);
x=ifs.tellg();
ifs.seekg(0,ios::beg);
s=new char[x];
ifs.read(s,x);
ifs.close();
ofstream is("image.txt");
for(int i=0;i<x;i++){
is<<(unsigned int)s[i]<<",";
}
现在这个程序用十进制数字创建image.txt,如下所示,429496729542949672564294967295429494967264,0,16,74,70,73,70,0,1,。。。。。。这里有些数字似乎是4字节长,s[i]只指一个字节,那么(int)s[i]怎么能返回一个大于255的大数字呢。请有人帮我做这件事。。。。谢谢
在您的机器上,char
似乎已签名。所以当你把一个负数转换成unsigned int
时,你会得到一个很大的值。当使用char
表示时,输出中的大值为负值。请注意,当char
有符号时,其值可以是-128
到127
,但字节可以在0
到255
之间。因此,任何大于127
的值在范围-128 to -1
之间都将变为负值。
使用unsigned char
作为:
unsigned char *s;
或者这样做:
is<< static_cast<unsigned int> (static_cast<unsigned char>(s[i]) )<<",";
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
casting to unsigned char first
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
then casting to unsigned int
也就是说,先将char
强制转换为unsigned char
,然后再强制转换为unsigned int
。
这就是你所面临的问题。现在请注意文体和习语。在C++中,应尽可能避免使用new
。在您的情况下,您可以将std::vector
用作:
//define file stream object, and open the file
std::ifstream file("image.jpg",ios::binary);
//prepare iterator pairs to iterate the file content!
std::istream_iterator<unsigned char> begin(file), end;
//reading the file content using the iterator!
std::vector<unsigned char> buffer(begin,end);
最后一行将文件中的所有数据读取到buffer
中。现在您可以将它们打印为:
std::copy(buffer.begin(),
buffer.end(),
std::ostream_iterator<unsigned int>(std::cout, ","));
为了使所有这些都起作用,除了您已经在代码中添加的内容外,还需要包括以下标题:
#include <vector> //for vector
#include <iterator> //for std::istream_iterator and std::ostream_iterator
#include <algorithm> //for std::copy
正如您所看到的,此惯用解决方案不使用指针和new
,也不使用强制转换!
相关文章:
- 在java中读取c++字节的位字段
- 从 C++ 中的标准输入迭代读取字节
- 写入/dev/ttyS0后读取0字节
- 提升 ASIO transfer_exactly读取 0 字节
- 读取字节后丢失指针
- 如何从文件中读取字节?C++
- AWS S3 CPP SDK读取字节多于指定的范围
- 从二进制文件中保存的 4 字节双精度读取 8 字节双精度
- 从 midi 文件读取字节时出现问题
- 串行读取字节 - Arduino 循环
- 将整数从处理发送到Arduino,无法读取字节
- 从文件到短 /长整数读取字节
- 使用C 中的字符指针从字符数组中读取字节
- 正在尝试读取4字节无符号整数的二进制文件并转换为伏特
- 从二进制文件中逐个读取字节
- 正在从二进制文件中读取字节
- 如何从无符号变量写入和读取字节
- 使用 ifstream 读取字节
- 从串行设备读取字节(并理解它们??)
- 如何从一个套接字读取' 1 '字节,而从另一个套接字读取' read_some '字节