Reputation: 177
I have code where the user inputs two chars into a string
variable. I have a function that verifies that the user input is only two chars long, and that it only contains valid hexadecimal digits.
I want to write these digits to a binary file that's 32 bytes long. I tried:
outFile.write((char*)&string[0], 1);
In a loop that runs 32 times (I want to write one byte at a time) to test, but it just writes the ascii code for the char, not the actual char itself. I expected it to write a nybble and skip a nybble, but it wrote a full byte of ascii information instead. So I tried:
outFile.write((unsigned char*)&string[0], 1);
But my compiler complains about it being an invalid cast.
I want to solve this problem without converting the string into a c-style string. In other words, I want string
to contain two chars and represent one byte of information. Not four (plus null characters).
Upvotes: 0
Views: 1716
Reputation: 177
As a workaround for your missing stoi you can do this:
#include <iostream>
#include <sstream>
#include <ios>
char hexnum[]{"2F"}; // or whatever, upper or lowercase hex digits allowed.
std::istringstream input(hexnum);
int num=0;
input >> std::hex >> num;
unsigned char byte = num;
outFile.write(static_cast<const char*>(&byte), 1);
Upvotes: 0
Reputation: 473537
You have a string that represents an integer. So convert the string to an integer:
unsigned char byte = (unsigned char)std::stoi(string, 0, 16);
outFile:write(static_cast<const char*>(&byte), 1);
Upvotes: 1