Joe
Joe

Reputation: 21

C++ Text File Reading

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.

Upvotes: 2

Views: 452

Answers (3)

rubenvb
rubenvb

Reputation: 76795

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.

Upvotes: 1

chrisaycock
chrisaycock

Reputation: 37928

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

Upvotes: 0

Martin Beckett
Martin Beckett

Reputation: 96177

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

Upvotes: 0

Related Questions