简体   繁体   English

C中的位屏蔽和分离

[英]Bit masking and separation in c

I am new to c programming and i need help in bit manipulation. 我是C编程的新手,我需要一些位操作方面的帮助。 I would like to separate the number from a register which have encoded numbers in BCD. 我想将数字与BCD中已编码数字的寄存器分开。 for example; 例如;

the register got '29' as value two bits will denote 2 ='10' and four bits will denote 9='1001'. 寄存器得到“ 29”,其值两位表示2 =“ 10”,而四位表示9 =“ 1001”。 It is an 8 bit register and rest bits are zero. 它是一个8位寄存器,其余位为零。 So shifting out the 4 bits will give me 2 at disposal.But what about getting the unit digit? 因此,移出4位将给我2个可用的值,但是获得单位数呢? I need some help regarding that I'm posting the code here: 我需要在此处发布代码方面的一些帮助:

  #include<stdio.h>
    main()
 {
     int x,y;
     y=0x29;
      x=y;
     x=x>>4;
    x=x*10;
    printf("%d",x);
    return(0);

 }

You need to mask it out with binary 00001111 , which is decimal 15 or hexadecimal 0x0f . 您需要使用二进制00001111 (十进制15或十六进制0x0f对其进行屏蔽。

uint8_t reg = 41; // binary 00101001
uint8_t lo_nibble = (reg >> 0) & 0x0f;
uint8_t hi_nibble = (reg >> 4) & 0x0f;

To form a mask to capture the bottom n bits of a number, you can perform these steps (pen and paper at first, eventually in your head): 要形成一个掩码以捕获数字的后n位,可以执行以下步骤(首先是笔和纸,最后是在头上):

  • start with the value 1. 从值1开始。
    (1) // == 1 or 00000001 (1) // == 1或00000001

  • shift the value 1 up by n bits. 将值1 n位。
    (1<<4) // == 16 or 00010000 (1<<4) // == 16或00010000

  • subtract 1. 减1。
    (1<<4)-1 // == 15 or 00001111 (1<<4)-1 // == 15或00001111

ANDing this mask with another value or variable will yield the bottom n bits of the number. 将此掩码与另一个值或变量进行“与”运算将产生数字的后n位。

int in, hi, lo;

lo = in & ((1<<4)-1);
hi = (in>>4) & ((1<<4)-1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM