我是靠谱客的博主 瘦瘦汽车,这篇文章主要介绍c定义16位整数和8位整数_C程序从另一个整数替换指定位置的整数中的位,现在分享给大家,希望可以做个参考。

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位。

复制代码
1
2
3
4
5
6
7
8
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

number 7

Second no: 8

第二名:8

number 8

Algorithm:

算法:

复制代码
1
2
3
4
5
6
7
8
9
10
11
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)

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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实现

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#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

输出量

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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程序从另一个整数替换指定位置内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(62)

评论列表共有 0 条评论

立即
投稿
返回
顶部