All answers so far suggested using *(short *)buf
, but that's not any good - it breaks the strict aliasing rule (the alignment of short
is greater than that of char
, so you can't do this without invoking undefined behavior).
The short answer is: you'd be better off using memcpy()
, but if you really don't want that, then you can use unions and "type punning" (note that this may result in a trap representation of the buffer of bytes which may or may not be what you want):
union type_pun {
char buf[sizeof(short)];
short s;
};
union type_pun tp;
tp.buf[0] = 0xff;
tp.buf[1] = 0xaa; // whatever, if `short' is two bytes long
printf("%hd\n", tp.s);