将十六进制写入文件 [英] Writing hex to a file

查看:88
本文介绍了将十六进制写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序来读取文件的 hex ,对其进行修改,然后将修改后的hex存储在 std :: string 中.

I have a program that reads the hex of a file, modifies it, and stores the modified hex in a std::string.

例如,如何将其写入文件

For example, how would I write this to a file

std::string wut="b6306edf953a6ac8d17d70bda3e93f2a3816eac333d1ac78";

并获得其价值

.0n..:j..}p...?*8...3..x

在输出的文件中?

我不想使用 sprintf ,但是我想如果有必要,我会做我必须做的事情.

I'd prefer not to use sprintf, but I guess if it's necessary, I'll do what I must.

推荐答案

如果我正确理解了您的问题,则希望将文本转换为等效的数字,然后再写入文件.根据您在问题中提供的提示,看起来应该逐个字节地完成.下面是实现此目的的一种方法.请注意,需要将每个字节从字符串转换为整数值.

If I understand your question correctly you want the text converted to it's numeric equivalent and then written to file. Given the hint you provided in your question it looks like this should be done byte by byte. Below is one way to achieve this. Note the need to convert each byte from a string to an integer value.

#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
#include <ios>

std::string wut = "b6306edf953a6ac8d17d70bda3e93f2a3816eac333d1ac78";

int main()
{
    std::ofstream datafile("c:\\temp\\temp1.dat", std::ios_base::binary | std::ios_base::out);

    char buf[3];
    buf[2] = 0;

    std::stringstream input(wut);
    input.flags(std::ios_base::hex);
    while (input)
    {
        input >> buf[0] >> buf[1];
        long val = strtol(buf, nullptr, 16);
        datafile << static_cast<unsigned char>(val & 0xff);
    }

}

这篇关于将十六进制写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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