题目:就是实现位的替换
原型:void append(unsigned char *s,int n,unsigned char *buf,int len)
说明:s为目标字符串,n为位数,buf为缓冲区,len为buf的长度。现在要在s中的第n位开始,赋上buf的值。
不能用动态内存分配函数。
求解答。
注意,我说的是位。。。。不是字节。。相当于是s中的第n位到第n+len位是buf的len位。
题目来自:http://topic.csdn.net/u/20111108/12/8eb961d4-7d35-4193-9ed4-ff3e71ca140e.html?85604
#include <stdio.h>
void append(unsigned char *s,int n,unsigned char *buf,int len);
void printa(unsigned char *a, int a_len);
int main(int argc, char *argv[])
{
unsigned char s[2] = {0x12,0x34};
unsigned char buf[2] = {0x45,0x56};
printa(s, sizeof(s));
printa(buf, sizeof(buf));
append(s, 2, buf, 3);
printa(s, sizeof(s));
printa(buf, sizeof(buf));
return 0;
}
void append(unsigned char *s,int n,unsigned char *buf,int len)
{
unsigned char bits[8] = {0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01};
int i;
for(i=0; i<len; ++i) {
int x = i+n-1;
if((*(buf+i/8)) & bits[i%8]) {
*(s+x/8) |= bits[x%8];
} else {
*(s+x/8) &= ~bits[x%8];
}
}
return;
}
void printa(unsigned char *a, int a_len)
{
int i;
for(i=0; i<a_len; ++i) {
printf("%02X ", a[i]);
}
printf("\n");
return;
}