2

So I need a little help, I've currently got a text file with following data in it:

myfile.txt ----------- b801000000 

What I want to do is read that b801 etc.. data as bits so I could get values for

0xb8 0x01 0x00 0x00 0x00. 

Current I'm reading that line into a unsigned string using the following typedef.

typedef std::basic_string <unsigned char> ustring; ustring blah = reinterpret_cast<const unsigned char*>(buffer[1].c_str()); 

Where I keep falling down is trying to now get each char {'b', '8' etc...} to really be { '0xb8', '0x01' etc...}

Any help is appreciated.

Thanks.

2
  • 1
    It looks like you want to read two bytes in at a time and then interpret as a hex code. An unsigned char is still just one byte. Commented Jan 26, 2011 at 18:06
  • 1
    duplicate of stackoverflow.com/questions/3825553/… Commented Jan 26, 2011 at 18:10

3 Answers 3

1

I see two ways:

  1. Open the file as std::ios::binary and use std::ifstream::operator>> to extract hexadecimal double bytes after using the flag std::ios_base::hex and extracting to a type that is two bytes large (like stdint.h's (C++0x/C99) uint16_t or equivalent). See @neuro's comment to your question for an example using std::stringstreams. std::ifstream would work nearly identically.

  2. Access the stream iterators directly and perform the conversion manually. Harder and more error-prone, not necessarily faster either, but still quite possible.

Sign up to request clarification or add additional context in comments.

Comments

0

strtol does string (needs a nullterminated C string) to int with a specified base

Comments

0

Kind of a dirty way to do it:

#include <stdio.h> int main () { int num; char* value = "b801000000"; while (*value) { sscanf (value, "%2x", &num); printf ("New number: %d\n", num); value += 2; } return 0; } 

Running this, I get:

New number: 184 New number: 1 New number: 0 New number: 0 New number: 0 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.