需要在C ++中以十六进制格式将字符串写入文件

时间:2019-05-10 07:18:48

标签: c++ file hex

我有一个包含十六进制值的字符串:

string str = "e101";

我需要将此文件写为2个字节。当我尝试写入文件时,它将像以下4个字节的值那样写入:

65 31 30 31

我正在使用以下操作进行文件写入:

    myfile.open ("file.cf3",std::ios::binary);
    myfile << str << "\n";
    myfile.close();

但是我想将其写为2个字节的值。

例如,如果我要如何将其作为2个字节写入文件?

std::string wut="b6306edf953a6ac8d17d70bda3e93f2a3816eac333d1ac78";

我想要类似的输出

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

3 个答案:

答案 0 :(得分:1)

这是解决方案的示例。

#include <fstream>
#include <iostream>
#include <string>

int main() {
    std::ofstream file("file.txt", std::ios::binary);
    if(!file.is_open())  {
        return -1;
    }
    std::string str("e101");
    for (std::size_t i = 0; i < str.length() - 1; ++++i) {
        file << static_cast<char>(str[i] * 16 + str[i + 1]);
    }
    file.close();
}

您可以简单地遍历字符串并将两个字符作为一个字节。您将第一个字符乘以16,然后添加第二个字符。

答案 1 :(得分:1)

我认为您的问题模棱两可... 请记住,从您的字符串开始,每两个字符都有1个字节(不是两个)。 因此,您要写两个数字(表示ASCII)代表字符串的十六进制值... 如果这是正确的解释,则需要将字符串分成多个字符对,然后将每个字符转换为等效的整数。 这是我的代码... 它会写到stdout,但是您可以轻松地对其进行修改,以便将其写入文件而不是写入屏幕。

implementation "android.arch.core:core-testing:1.0.0"

答案 2 :(得分:0)

要回答有关将二进制文件中的2字节写入C ++中文件的原始问题,您有一个基本的两步过程。 (1)使用以stoi为底的16将数字的字符串表示形式转换为数值。这提供了可以存储在unsigned short中的数值。 (2)使用f.write而不是frwite将该值写到文件中,其中f是您的开放流引用。

如果要为cout以十六进制格式设置输出格式,则必须为cout设置标志以以十六进制格式输出数值(尽管不是问题的直接组成部分,它还是有关系的)在流I / O格式(如果需要)中。)

因此,基本上,您拥有字符串并将其转换为数字,例如

    std::string str = "e101";
    unsigned short u = stoi(str, 0, 16);

现在u保留一个使用{em> base-16 从str中的文本转换而来的数值,您可以简单地将其写为2字节的值,例如

    std::string filename = "out.bin";   /* output filename */
    ...
    std::ofstream f (filename, f.trunc | f.binary); /* open out in binary */
    if (!f.write(reinterpret_cast<char*>(&u), sizeof u)) {  /* write 2 bytes */
        std::cerr << "error: write of short to file failed.\n";
        return 1;
    }

将其完全放在一起,您可以做一些简短的操作,例如输出用cout写入的十六进制值,以及将其写入文件"out.bin"

#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>

int main (void) {

    std::string filename = "out.bin";   /* output filename */
    std::string str = "e101";
    unsigned short u = stoi(str, 0, 16);
    /* output converted value to terminal in hex */
    std::cout.setf(std::ios::hex, std::ios::basefield);  /* set hex output */
    std::cout << "writing value to file: " << u << '\n'; /* for cout */
    /* output converted value to file */
    std::ofstream f (filename, f.trunc | f.binary); /* open out in binary */
    if (!f.write(reinterpret_cast<char*>(&u), sizeof u)) {  /* write 2 bytes */
        std::cerr << "error: write of short to file failed.\n";
        return 1;
    }
}

使用/输出示例

$ ./bin/stoi_short
writing value to file: e101

生成的输出文件

通过使用hexdump程序转储文件内容进行确认,例如

$ hexdump out.bin
0000000 e101
0000002

仔细检查一下,如果还有其他问题,请告诉我。

相关问题