概述
c定义16位整数和8位整数
Problem statement: Write a C program to replace specified bit of a number from another number.
问题陈述:编写一个C程序,以从另一个数字替换一个数字的指定位 。
Solution: We can use bitwise operator here to solve the problem.
解决方案:我们可以在这里使用按位运算符来解决问题。
In this solution we have considered 8 bits representation which can be extended up to 32 bits using the same idea.
在此解决方案中,我们考虑了8位表示,使用相同的思想可以将其扩展到32位。
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)
First no: 7
第一次没有:7
Second no: 8
第二名:8
Algorithm:
算法:
IF specified bit at second no is 1
1) Form a bit mask (0, d)
0 - for all position except the bit specified
d - 1 at specified position(dth)
2) Do bitwise OR between the first no and the mask
ELSE //specified bit at second no 0
1) Form a bit mask (1, d)
1 - For all position except the bit specified
d - 0 at specified position (dth)
2) Do bitwise AND between the first no & the mask.
Forming the bitmask (0, d)
形成位掩码(0,d)
Let the specified position d.
Declare temp as (second>>d) & 1
Right shift second number d times to get the dth bit as LSB
Bitwise AND with 1
This results in 0000 000di(where diis the dth bit of second no)
Left shift temp d times. This results in our desired bitmask(0, d)
Forming the bitmask (1, d)
Declare flag 255;//FF, all bit set to 1(considering 8 bit)
Declare temp as 1<<d;
Do bitwise XOR between flag and temp
//this sets only the specified position bit 0 and others with 1
This results in our desired bitmask (1, d)
C implementation
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)
temp=1<<pos;
//this set only the specified position bit 0 others 1
flag=flag^temp;
first&=flag;
}
printf("converted no %dn",first);
return 0;
}
Output
输出量
First run:
enter first & second no:
7 8
enter specified position(0-indexed)
3
converted no 15
Second run:
enter first & second no:
7 8
enter specified position(0-indexed)
2
converted no 3
翻译自: https://www.includehelp.com/c-programs/replace-bit-in-an-integer-at-a-specified-position-from-another-integer.aspx
c定义16位整数和8位整数
最后
以上就是瘦瘦汽车为你收集整理的c定义16位整数和8位整数_C程序从另一个整数替换指定位置的整数中的位的全部内容,希望文章能够帮你解决c定义16位整数和8位整数_C程序从另一个整数替换指定位置的整数中的位所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复