c语言找到一个十六进制数的某一位并替换 20
#include<stdio.h>
unsigned int SetBit(unsigned int *num, int pos, int value);
void main()
{
unsigned int a = 0x1234abcd;
printf("a=0x%08x\n",a);
printf("a(0,0)=0x%08x\n",SetBit(&a,0,0));
printf("a(0,1)=0x%08x\n",SetBit(&a,0,1));
printf("a(31,1)=0x%08x\n",SetBit(&a,31,1));
printf("a(31,0)=0x%08x\n",SetBit(&a,31,0));
printf("a(28,0)=0x%08x\n",SetBit(&a,28,0));
printf("a(28,1)=0x%08x\n",SetBit(&a,28,1));
}
/*
将num第pos位设置为value
pos取值范围0-31
value取值范围0,1
*/
unsigned int SetBit(unsigned int *num, int pos, int value)
{
*num &= ~(1<<pos); //将*num的第pos位设置为0
*num |= value<<pos;
return *num;
}
{
if( bit <0 || bit >sizeof(int)*2 )
return -1;
if( value <0 || value > 15 )
return -2;
char tmp=0x0f;
char tmp_high=0xf0;
unsigned char * pos=(unsigned char*)value;
pos += (bit / 2);
if( bit %2 != 0)
{
value >>= 4;
value &= tmp_high; //去掉低位
*pos &= tmp; //去掉高位
*pos |= value;
}
else
{
value &= tmp; //去掉高位
*pos &= tmp_high; //去掉低位
*pos |= value;
}
return 0; //成功。
}