Polaris431 wrote:
I have a buffer that holds characters. Four characters in a row
represent an unsigned 32 bit value. I want to convert these characters
to a 32 bit value.
Do the four characters contain text representing a value, or do they
contain the bit image of a value?
char numstr[] = "1234";
unsigned char bitbuf[] = { 0x01, 0x02, 0x03, 0x04 };
unsigned long val1, val2;
val1 = strtoul( numstr, NULL, 10 ); /* val1 = 1234 */
val2 = bitbuf[ 3 ] << 24 | /* val2 = 0x04030201 */
bitbuf[ 2 ] << 16 | /* = 67305985 */
bitbuf[ 1 ] << 8 |
bitbuf[ 0 ];
For example:
char buffer[3];
buffer = "aabbccdd";
where aa is the LSB and dd is the MSB.
This is going to hopelessly confuse people here, who will interpret what
you've written as literal C code: You create a char array of length 3,
not 4, and then try to put 8 chars in it, using an invalid assignment.
Correct me if I'm wrong, but I think you meant "[4]", and that you're
trying to say that buffer[] contains the bit image of a 32-bit integer
in little-endian byte order.
I thought of making a pointer to point to the address of the value
variable and copy each character into the location but I can't figure
out how to do that, if it is even possible at all.
It's not uncommon to see something that works the other way around,
forming a pointer to the character array and reinterpreting what it
points to:
val2 = *(( unsigned long * ) &bitbuf );
This takes the address of bitbuf, interprets it as a pointer to
unsigned long, then dereferences that pointer and assigns the value.
This sometimes works, but it's not portable. It assumes that the byte
order of long is the same as the order of the bytes in bitbuf[] on the
host platform, that sizeof long is 4, and that the address of bitbuf[0]
is aligned properly for a long on the host platform.
I had another solution of converting each character to a byte and
shifting it into the value variable but I want to avoid shifting due
to the overhead required for shifting on my target system.
Bit shifting is typically just about the fastest thing you can do.
The bit shifting and bitwise-OR in
val2 = bitbuf[ 3 ] << 24 |
bitbuf[ 2 ] << 16 |
bitbuf[ 1 ] << 8 |
bitbuf[ 0 ];
can be replaced by multiplication and addition,
val2 = bitbuf[ 3 ] * 0x1000000 +
bitbuf[ 2 ] * 0x10000 +
bitbuf[ 1 ] * 0x100 +
bitbuf[ 0 ];
but I'd be very surprised if the second form was faster than the first
on any platform.
- Ernie
http://home.comcast.net/~erniew