Re: Hexa reading from a file
On Mar 1, 10:58 am, "Chandra" <forquer...@gmail.com> wrote:
I have a problem related to File Reading. I have a file which contains
data which is in Hexa format. I have to read that data and push it to
a function which takes a parameter of type char. I am able to read the
data from the file, which i am getting as characters.
For example: Suppose the Hexa value from the File data is ABCDEFGH. In
hexa form 0xAB is one byte. So, while reading this data A is taken as
a byte which is not a required format. I am supposed to get AB as a
byte, which i am not getting.
First, the common abbreviation for hexadecimal is hex (cf. std::hex),
not hexa. Second, G and H are not valid hexadecimal values.
Now, let's say have a std::string with "ABCDEF" and you want to divide
it up into 8-bit bytes. You could do something like this (untested):
const string str = "ABCDEF";
const unsigned i = ConvertString<unsigned>( "0x" + str.substr( 0,
2 ) ); // Parameter yields "0xAB"
assert( i == 0xAB );
where
template<typename T>
T ConvertString( const std::string& s )
{
std::istringstream iss( s );
T t;
if( !(iss >> std::resetiosflags( std::ios::basefield ) >> t >>
std::ws).eof() )
throw std::invalid_argument( "Unable to convert \"" + s +
"\"" );
return t;
}
See also http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.2
and the docs on Boost's lexical_cast (http://boost.org/libs/conversion/
lexical_cast.htm).
Now, assuming I typed everything correctly, you just need to put it in
a loop to extract the rest of the values. Also note that the
conversion function throws an exception if the input is invalid, so
you'll need to handle that.
Cheers! --M