This is the same technique as already presented, but it is targeted toward the original intent: two (presumably unsigned char) pointers and two bit locations.Quote:
Originally posted by Coder2Die4
I have 2 pointers, let's call them source_ptr and destination_ptr. I want to copy 1 bit from the source byte to another bit of the destination byte. Are there a simple instruction to do that?
Example: source bit 2 to destination bit 5
Note also that my bits (srcbit, dstbit) are 'numbered' 0-7 rather than the example that had them as 1-8.Code:#include <stdio.h>
#include <limits.h>
void bitcpy(unsigned char *dst, unsigned char dstbit,
const unsigned char *src, unsigned char srcbit)
{
if ( *src & (1 << srcbit) ) /* if srcbit is '1' in source byte */
{
*dst |= (1 << dstbit); /* set dstbit in destination byte */
}
else /* else srcbit is '0' in source byte */
{
*dst &= ~(1 << dstbit); /* clear dstbit in destination byte */
}
}
void showbits(unsigned char byte)
{
unsigned char bit;
printf("0x%02X = ", byte);
for ( bit = 1 << ((sizeof(byte) * CHAR_BIT) - 1); bit; bit >>= 1 )
{
putchar(byte & bit ? '1' : '0');
}
putchar('\n');
}
int main(void)
{
int i;
unsigned char result = 0xFF, value = 0x3A;
fputs("result: ", stdout); showbits(result);
fputs("value: ", stdout); showbits(value);
bitcpy(&result, 5, &value, 2);
puts("*** bitcpy ***");
fputs("result: ", stdout); showbits(result);
puts("*** reverse bits ***");
fputs("value: ", stdout); showbits(value);
for ( i = 0; i < CHAR_BIT; ++i )
{
bitcpy(&result, (CHAR_BIT - 1) - i, &value, i);
}
fputs("result: ", stdout); showbits(result);
return 0;
}
/* my output
result: 0xFF = 11111111
value: 0x3A = 00111010
*** bitcpy ***
result: 0xDF = 11011111
*** reverse bits ***
value: 0x3A = 00111010
result: 0x5C = 01011100
*/