在程序开发过程中,我们经常会用到按位拷贝一串二进制数,在此提供一个按位拷贝的函数给大家参考,函数源码如下:
1 #define char_t char 2 #define uint8_t unsigned char 3 #define int8_t signed char 4 #define uint16_t unsigned short 5 #define int16_t signed short 6 #define uint32_t unsigned long int 7 #define int32_t signed long int 8 9 /* 10 * param[in] SrcData: source data 11 * param[in] StartsrcBit: start source bit(1, 2, 3, ...) 12 * param[in] startdstbit: start destination bit(1, 2, 3, ...) 13 * param[in] CopyLen: copy length 14 * param[out] DstData: destination data 15 */ 16 void copy_data_by_bits(uint8_t *DstData, uint32_t startdstbit, uint8_t *SrcData, uint32_t StartsrcBit, uint32_t CopyLen) 17 { 18 uint32_t copysrcbyte = 0; 19 uint32_t copysrcbitofbyte = 0; 20 uint32_t copydstbyte = 0; 21 uint32_t copydstbitofbyte = 0; 22 uint32_t dataLen = CopyLen; 23 24 if ((NULL == SrcData) || (NULL == DstData)) { 25 printf("SrcData or DstData is NULL !!! "); 26 return; 27 } 28 29 while (dataLen > 0) { 30 copydstbyte = ((startdstbit + dataLen) / 8); 31 copydstbitofbyte = ((startdstbit + dataLen) % 8); 32 copysrcbyte = ((StartsrcBit + dataLen) / 8); 33 copysrcbitofbyte = ((StartsrcBit + dataLen) % 8); 34 35 if (0 == copysrcbitofbyte) { 36 copysrcbitofbyte = 8; 37 copysrcbyte = copysrcbyte - 1; 38 } 39 40 if (0 == copydstbitofbyte) { 41 copydstbitofbyte = 8; 42 copydstbyte = copydstbyte - 1; 43 } 44 45 DstData[copydstbyte] &= ~(1 << (copydstbitofbyte - 1)); 46 if ((SrcData[copysrcbyte] & ((uint8_t)((uint8_t)1 << (copysrcbitofbyte - 1)))) != 0) { 47 DstData[copydstbyte] |= ((uint8_t)1 << (copydstbitofbyte - 1)); 48 } 49 dataLen--; 50 } 51 }
测试代码:
1 int main(void) 2 { 3 uint8_t SrcData[] = {0x12, 0x34, 0x56, 0x78}; 4 uint32_t StartsrcBit = 3; 5 uint32_t CopyLen = 8; 6 uint8_t DstData[2] = {0}; 7 uint32_t startdstbit = 8; 8 9 DstData[0] = 0xab; 10 copy_data_by_bits(DstData, startdstbit, SrcData, StartsrcBit, CopyLen); 11 printf("DstData[0]:%#04x DstData[1]:%#04x ", DstData[0], DstData[1]); 12 13 return 0; 14 }
分析如下: