嵌入式c中的位提取

时间:2017-08-29 03:03:00

标签: c

我正在从给定的字节中提取位。我在二进制1111中有32位0XFA73DECB 10 10 0111 0011 1101 11 10 1100 1011.Now如何提取位号。 7到22?有人帮帮我吗?

2 个答案:

答案 0 :(得分:0)

以下代码首先将这些位提取到另一个int中,然后以二进制形式输出。

#include <stdio.h>
#include <stdlib.h>
unsigned int a = 0xfa73decb;
int main()
{
    unsigned int Bits = 0b00000011111111111111110000000000;
    unsigned int Extract = (a & Bits) >> 10;
    char Bin[20];
    _itoa(Extract, Bin, 2);
    printf("%s\n", Bin);
    while (1);
}

_itoa(下划线是因为我使用Visual Studio并且不推荐使用典型的itoa)意味着将整数Extract转换为基数为2的字符串并将其存储到字符串Bin

答案 1 :(得分:0)

动态读取输入以提取位,

#include <stdio.h>
#include <stdlib.h>
unsigned int a = 0xfa73decb;

int main()
{
   int msb;
   int lsb;
   unsigned int Extract;

   printf("size of unsigned int = %d\n", sizeof(unsigned int));     // sizeof int : 4 bytes (32 bits)

   scanf("%d", &lsb);              // as per your requirement: 10
   scanf("%d", &msb);              // as per your requirement: 26

   msb = (8*sizeof(unsigned int)) - msb;         // msb = 32 - 26 ; // 6 
   lsb = lsb + msb ;                             // lsb = 10 + 6 ;  // 16

   Extract = (a << msb);                        // shifting 6 times left
   printf("After Left shift = 0x%0x\n", Extract);
   Extract = Extract >> lsb;                   // shifting 16 times right
   printf("After Right shift = 0x%0x\n", Extract);

}

输入:

10 26

输出:

size of unsigned int = 4
After Left shift = 0x9cf7b2c0
After Right shift = 0x9cf7