I'm completely new to C++, so I guess this might be a very trivial question. If this is a duplicate of an already answered question (I bet it is...), please point me to that answer!
I have a file with the following cut from hexdump myfile -n 4
:
00000000 02 00 04 00 ... |....|
00000004
My problem/confusion comes when trying to read these values and convert them to ints ( [0200]_hex --> [512]_dec and [0400]_hex --> [1024]_dec).
A minimum working example based on this answer:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(void){
char fn[] = "myfile";
ifstream file;
file.open(fn, ios::in | ios::binary);
string fbuff = " ";
file.read((char *)&fbuff[0], 2);
cout << "fbuff: " << fbuff << endl;
// works
string a = "0x0200";
cout << "a: " << a << endl;
cout << "stoi(a): " << stoi(a, nullptr, 16) << endl;
// doesn't work
string b = "\x02\x00";
cout << "b: " << b << endl;
cout << "stoi(b): " << stoi(b, nullptr, 16) << endl;
// doesn't work
cout << "stoi(fbuff): " << stoi(fbuff, nullptr, 16) << endl;
file.close();
return(0);
}
What I cant get my head around is the difference between a
and b
; the former defined with 0x
(which works perfect) and the latter defined with \x
and breaks stoi. My guess is that whats being read from the file is in the \x
-format, based on the output when running the code within sublime-text3 (below), and every example I've seen only deals with for example 0x0200
-formatted inputs
// Output from sublime, which just runs g++ file.cpp && ./file.cpp
fbuff: <0x02> <0x00>
a: 0x0200
stoi(a): 512
b:
terminate called after throwing an instance of 'std::invalid_argument'
what(): stoi
[Finished in 0.8s with exit code -6]
Is there a simple way to read two, or more, bytes, group them and convert into a proper short/int/long?