Question about bitmasks and how i can extract 7 bits from a 16bit sequence in C

80 Views Asked by At

i came across bitmasks to a code that i am making , but since i am a newbie and its the first time practising with bitmasks i want to understand them better.

So i have an example, that i want to get the first 7 bits of a 16 bit number that is unsigned short int type ,store them into a new integer and print them in decimal. I have tried the code below but i get random results. I would appreciate any help.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>


int main(int argc, char *argv[]) {
unsigned short int num,mask1=127,final1;


scanf("%hx",&num);
printf("%hx\n",num);



final1=num&(mask1>>9);  

printf("Final is %hu\n",final1);

    return 0;
}

So for example when i put a random hex value like 0x3f23 the bit sequnce is 0011111100100011 . So i want to get the 7 first bits extracted which is my case is 0011111 . My initial thought was to use bit shift to the right to move the first 7 bits to the end of the sequence like this (which means 9 bits to the right) 0000000000011111 but since i am a newbie i have trouble getting a proper result from the above thought

0

There are 0 best solutions below