将十六进制数据输出到文件的正确方法是什么? [英] What is the correct way to output hex data to a file?

查看:152
本文介绍了将十六进制数据输出到文件的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已阅读过 [ostream]<< hex<< 0x(十六进制值),但我有一些问题

I've read about [ostream] << hex << 0x[hex value], but I have some questions about it

(1)我定义了我的文件流,输出,使用 output.open(BWhite.bmp,ios :: binary); 是否会使输出<< 操作中的 hex 参数多余?

(1) I defined my file stream, output, to be a hex output file stream, using output.open("BWhite.bmp",ios::binary);, since I did that, does that make the hex parameter in the output<< operation redundant?

(2)
如果我有一个整数值,我想存储在文件中,我使用这个:

(2) If I have an integer value I wanted to store in the file, and I used this:

int i = 0;
output << i;

会存储在小端序还是大端序?将根据程序在哪个计算机上执行或编译来更改内容?

would i be stored in little endian or big endian? Will the endi-ness change based on which computer the program is executed or compiled on?

此值的大小取决于运行的计算机吗?我需要使用十六进制参数吗?

Does the size of this value depend on the computer it's run on? Would I need to use the hex parameter?

(3)有没有办法输出原始十六进制数字到文件?如果我想要该文件的十六进制数字43,我应该使用什么?

(3) Is there a way to output raw hex digits to a file? If I want the file to have the hex digit 43, what should I use?

输出<< 0x43 输出<< hex<< 0x43 都输出ASCII 4,然后输出ASCII 3。

output << 0x43 and output << hex << 0x43 both output ASCII 4, then ASCII 3.

输出这些十六进制数字的目的是为.bmp文件创建标题。

The purpose of outputting these hex digits is to make the header for a .bmp file.

推荐答案

格式化的输出运算符<< :格式化输出。

The formatted output operator << is for just that: formatted output. It's for strings.

因此, std :: hex 流操纵器指示流输出数字作为字符串格式如十六进制。

As such, the std::hex stream manipulator tells streams to output numbers as strings formatted as hex.

如果要输出原始二进制数据,请仅使用未格式化的输出函数 basic_ostream :: put basic_ostream :: write

If you want to output raw binary data, use the unformatted output functions only, e.g. basic_ostream::put and basic_ostream::write.

你可以输出一个类似这样的int:

You could output an int like this:

int n = 42;
output.write(&n, sizeof(int));

此输出的字节序将取决于架构。如果你想有更多的控制,我建议如下:

The endianness of this output will depend on the architecture. If you wish to have more control, I suggest the following:

int32_t n = 42;
char data[4];
data[0] = static_cast<char>(n & 0xFF);
data[1] = static_cast<char>((n >> 8) & 0xFF);
data[2] = static_cast<char>((n >> 16) & 0xFF);
data[3] = static_cast<char>((n >> 24) & 0xFF);
output.write(data, 4);

此示例将输出一个32位整数作为小尾数,无论平台的字节顺序如何。但是,如果 char 已签名,请小心转换。

This sample will output a 32 bit integer as little-endian regardless of the endianness of the platform. Be careful converting that back if char is signed, though.

这篇关于将十六进制数据输出到文件的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆