将十六进制写入文件C ++

编程入门 行业动态 更新时间:2024-10-27 02:23:46
本文介绍了将十六进制写入文件C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

所以我知道这个问题已经被问过很多次了.很抱歉再次提出要求,但我没有发现关于我的具体情况的任何疑问.

So I know this question has been asked many times. I'm sorry for asking again, but I haven't found any questions asked before with my specific circumstances.

因此,我有一个程序可以读取文件的十六进制,对其进行修改,然后将修改后的十六进制存储在std :: string中. 因此,例如,我如何将其写入文件

So I have a program that reads the hex of a file, modifies it, and stores the modified hex in an std::string. So 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.

谢谢大家, 〜P

推荐答案

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

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); } }

更多推荐

将十六进制写入文件C ++

本文发布于:2023-10-27 18:31:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1534188.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   将十六进制

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!