Ahmad Raza Ahmad Raza - 3 months ago 14
C Question

How can I get a value from particular number?

I have a hexadecimal value 0x40BF00FF and i want to get this value 0xFF (last two number) from it and other numbers are ignore. how can we write code in C language

Answer Source

If you are having a hex value (not a string). This small program can be a good example:

This method extracts the individual nibble. And then joins them back.

We can get the least significant 4-bits by taking modulus with 16. Then we can do left shift 4 times (divide by 16). And then extract the next least significant 4-bits.

Now we got the 8 LSB. Now we just append them.

#include <stdio.h>

int main()
{
    unsigned int x = 0x40BF00FF;

    // Extracting the first 4 least significant bits.
    unsigned int one = x % 16;

    // Extracting the next 4 least significant bits.
    unsigned int two = (x >> 4) % 16;

    // Appending the bits and printing the result.
    printf ("%x\n", (two << 4) + one);

    return 0;
}

OR

You can use the power of bits!

Here, the input is stored in x.

I take a mask 0xFF.

And I perform bitwise and operation.

Now, as we know

b&1 = b and b&0 = 0.

We can use this property to extract only the lower 8 bits by setting them all to 1 and others as 0. And performing a bitwise and (&).

#include <stdio.h>

int main()
{
    unsigned int x = 0x40BF00FF;

    // The mask.
    unsigned int mask = 0xFF;

    // Applying bitwise and
    printf ("%x\n", x & mask);

    return 0;
}