How to extract specific bits from a number in C?

后端 未结 8 1323
遥遥无期
遥遥无期 2020-12-08 07:35

I need to extract specific part (no of bits) of a short data type in C.

For Example I have a binary of 52504 as 11001101000 11000 and I want First 6 (

8条回答
  •  -上瘾入骨i
    2020-12-08 08:26

    // This is the main project file for VC++ application project 
    // generated using an Application Wizard.
    
    #include "stdafx.h"
    
    #using 
    
    using namespace System;
    
    
    void fun2(int *parr)
    {
        printf(" size of array is %d\n",sizeof(parr));
    }
    void fun1(void)
    {
        int arr[100];
        printf(" size of array is %d\n",sizeof(arr));
        fun2(arr);
    }
    
    int extractBit(int byte, int pos) 
    {
        if( !((pos >= 0) && (pos < 16)) )
        {
            return 0;
        }
        return ( ( byte & (1<> pos);
    }
    int extractBitRange(int byte, int startingPos, int offset) 
    {
    
    
       if(  !(((startingPos + offset) >= 0) && ( (startingPos + offset) < 16)) )
       {
            return 0;
       }
       return ( byte >> startingPos ) & ~(0xff << (offset + 1));
    }
    
    int _tmain()
    {
        // TODO: Please replace the sample code below with your own.
    
        int value;
        signed int res,bit;
        signed int stPos, len;
        value = 0x1155;
        printf("%x\n",value);
        //Console::WriteLine("Hello World");
        //fun1();
        for(bit=15;bit>=0;bit--)
        {
            res =extractBit(value,bit);
            printf("%d",res);
        }
        stPos = 4;
        len = 5;
        res = extractBitRange(value, stPos, len);
        printf("\n%x",res);
    
        return 0;
    }
    

提交回复
热议问题