-1

I'm trying to get an int value from a file I read. The trick is that I don't know how many bytes this value lays on, so I first read the length octet, then try to read as many data bytes as length octet tells me. The issue comes when I try to put the data octets in an int variable, and eventually print it - if the first data octet is 0, only the one that comes after is copied, so the int I try to read is wrong, as 0x00A2 is not the same as 0xA200. If i use ntohs or ntohl, then 0xA200 is decoded wrong as 0x00A2, so it does not resolve the hole problem. I am using memcpy like this:

memcpy(&dst, (const *)src, bytes2read)   

where dst is int, src is unsigned char * and bytes2read is a size_t.

So what am I doing wrong? Thank you!

Borgleader
  • 15,826
  • 5
  • 46
  • 62
veliki
  • 41
  • 1
  • 8

1 Answers1

5

You cannot use memcpy to portably store bytes in an integer, because the order of bytes is not specified by the standard, not speaking of possible padding bits. The portable way is to use bitwise operations and shift:

unsigned char b, len;
unsigned int val = 0;
fdin >> len;             // read the field len
if (len > sizeof(val)) { // ensure it will fit into an
    // process error: cannot fit in an int variable
    ...
}
while (len-- > 0) {      // store and shift one byte at a bite
    val <<= 8;           // shift previous value to leave room for new byte
    fdin >> b;           // read it
    val |= b;            // and store..
}
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252