Hexa reading from a file

C

Chandra

Hi,

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.

Hope you people understand my query.

with regards,

Chandra.
 
M

mlimber

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top