开发者

Writing a hexadecimal number to a file

How can I write the string representation of a hexadecimal number into a file? For example, if I have a hexadecimal value 0x001A (which is 26 i开发者_如何学Cn decimal) I want it written to a file as a hexadecimal string 0x001A and not as a decimal string 26 or a stream of the raw bytes.


You can force hexadecimal writing of numbers using the std::hex modifier:

std::cout << std::hex << 10 << std::endl;

This outputs "a". You can add the "0x" to have the representation complete. You can also turn them into uppercase by adding the std::uppercase after the std::hex to output the hexadecimal number in uppercase letters, also std::setfill('0') to fill the left sizes with '0', and std::setw(X) to set the desired width.

So, for example, 3 hex digits, uppercase letters and a '0' fill:

std::cout << "0x" << std:hex << std::uppercase << std::setw(3) << std::setfill('0') << 10 << std::endl;

will print exactly "0x00A".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜