Hi,

I have an unsigned char c[16] and I need to read 2 char at a time and put those in an index. Heres what I have so far.

std::istream& function(std::istream& aIStream){

    for (int i = 0; i < fSize; i++)
    {   
        //this is not working..
        // I tried static_cast<char*> and reinterpret_cast<char*> to type cast my c
        aIStream.read((char*)c[i], 2);
    }

    return aIStream;
}

all thats in the file, if you're curious, are 4C61 6D62 6461 462F 5368 6966 7456 616C.

What I want to happen is: c[16] = { 4c, 61, 6d, ... , 6c}

These are hexadecimal values, not characters. If you try to read them as characters, you will end up with the character array containing something like this:

c[16] = {'4', 'C', '6', '1', ' ', '6', ..., 'C'}

You need to read them as hexadecimal numbers. Here is how you do that:

unsigned int temp;
aIStream >> std::hex >> temp;
// Now, temp contains the two-byte value:
c[i]   = temp & 0xFF;         // first byte
c[i+1] = (temp >> 8) & 0xFF;  // second byte

That's basically how it's done.

2 byte increment please:

for(int i = 0; i < fSize; i += 2) {
  char buf[2] = "";
  aIStream >> buf[i] >> buf[i+1] >> flush;

  // Do something with buf[1st] & buf[2nd] here.
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.