Some machines have alignment restrictions for wider integer types like short or long. The pointer-cast approach described above will raise an exception on such a machine unless you are careful about alignment.
You can avoid alignment problems by copying bytes from your big byte array into a union. I've seen this done a lot, but the results are certainly implementation dependent. I think you're relying on undefined behavior, and that's always a bad idea.
- union ab {
-
unsigned char a[4];
-
long b;
-
};
The most reliable and portable way to do this is to start with a clear specification how the byte stream relates to the wider integer types, especially endianness and representation of negative values. They write software that explicitly implements the specification without relying on your machine happening to match the specification.
For example, if your specification says negative numbers are represented in the byte stream using two's-complement, then assemble the bytes in an unsigned type, test the sign bit, if it is set then use explicit logic to negate it (convert it to the equivalent positive number by inverting the bits and adding one), copy the positive value to a signed variable, and then use the unary-minus operator to negate it. This should work regardless of whether your machine uses two's-complement representation or not.