M
Maxim Yegorushkin
Provided l lifetime is same or longer than that of bytes.Your method ignores padding bits (if any, normally none on popular x86
and x86-64 platforms) and byte order.http://en.wikipedia.org/wiki/EndiannessTo make it byte order insensitive and ignore any padding bits you
could do:#include <stdio.h>
#include <limits.h>template<class T>
void asBytes(T t, unsigned char* bytes)
{
for(int i = 0; i != sizeof t; ++i)
bytes = static_cast<unsigned char>(t >> i * CHAR_BIT &
0xff);
}
template<class T>
void fromBytes(unsigned char const* bytes, T* t)
{
*t = 0;
for(int i = 0; i != sizeof t; ++i)
*t |= bytes << CHAR_BIT * i;
}
int main()
{
long l = 0x12345678;
unsigned char bytes[sizeof l];
asBytes(l, bytes);
long m;
fromBytes(bytes, &m);printf("%lx -> %lx\n", l, m);
}Obviously, the above two functions only work with integer types.
Dang!!! From a seemingly simple problem to several inscrutable lines of
C. This is not to say you're wrong -- I think you're exactly right. It's
more of a comment on the state of things; the nature of C, the compiler
implementations, the uncertain length of words in memory, the
endian-ness of the CPUs, etc., etc.
It's a shame that we can't use more direct approaches. That we are
willing to accept complex solutions, or uncertain definitions for
fundamental things like byte,word, and long, seems to me a great shame.
Whatever happened to KISS?
Well, this is what C and C++ are - portable assembly languages (as the
original purpose of C was to write a portable operating system called
UNIX and C++ inherits C and builds upon it). It is portable because it
abstracts away the CPU instruction set, however, you are still dealing
with the bare metal.