我下面有一个C程序,它将从另一个数字替换一个数字的指定位。例如:
Let first no whose bit is to be replaced is:
7 //0000 0111
Second no from whom bit is to be replaced
8 //0000 1000
Specified position: 3 (0-indxed)
Converted number will be 15
C代码:
#include <stdio.h>
int main()
{
int first,second,pos;
printf("enter first & second no:\n");
scanf("%d %d",&first,&second);
printf("enter specified position(0-indexed)\n");
scanf("%d",&pos);
//collect corresponding bit of second no
int temp=(second>>pos)&1;
//if bit at specified position is 1
if(temp==1){
temp=temp<<pos;
first|=temp;
}
else{ //if bit at specified position is 0
int flag=255;//FF, all bit set to 1(considering 8 bit numbers)
temp=1<<pos;
//this set only the specified position bit 0 others 1
flag=flag^temp;
first&=flag;
}
printf("converted no %d\n",first);
return 0;
}
值得庆幸的是,这对于8位整数都可以正常工作。我的问题是我需要程序最多可以处理32位整数(正整数小于30亿)。每当我使用较大的数字(例如20亿)时,它不会输出正确的转换后的数字。如何解决此问题?
那是因为您正在使用int。 32个有符号的int的最大值为:2 ^ 31您应该使用unsigned int解决您的问题。无符号32位int的最大值为:2 ^ 32。