Setting a bit in hexadecimal number

2.9k views Asked by At

Given a number (int a = 0XABCDE98) I am trying to set the D bit to 6. ie after the Bit manipulation the number should be (0XABC6E98).

I have written a small C program to do the bit manipulation, but somehow I am not able to see the correct bit change. Please help me in finding what might be missing in the program.

#include<stdio.h>

int main()
{
    int n = 0xABCDE98;
    n |= (n & 0X0000) | 0x6000;
    printf("%x\n", n);
    return 0;
}

o/p - abcfe98
6

There are 6 answers

0
Paul R On BEST ANSWER

Change:

n |= (n & 0X0000) | 0x6000;

to:

    n &= ~0xd000;
    n |=  0x6000;

or just:

    n = (n & ~0xd000) | 0x6000;

if you prefer.

Test:

#include <stdio.h>

int main()
{
    int n = 0xABCDE98;
    n &=   ~0x000d000;     // clear nybble
    n |=    0x0006000;     // set nybble to 6
    printf("%#x\n", n);
    return 0;
}

Compile and run:

$ gcc -Wall temp.c && ./a.out
0xabc6e98

LIVE CODE

2
Vagish On

Try This:

#include<stdio.h>

int main()
{
    int n = 0xABCDE98;
    n = n ^ 0x000B000;  //Ex-OR 'n' with  0x000B000
    printf("%x\n", n);
    return 0;
}

o/p - abc6e98
0
LPs On

In your code

n |= (n & 0X0000) | 0x6000;

is wrong beacuse of is equal to

0xABCDE98 & 0x0000 = 0 and 0x0000 | 0x6000 = 0x6000 and 0xABCDE98 | 0x6000 = 0xABCFDE98

Instead you must write

n = (n & 0XFFF0FFF) | 0x6000;
0
Vlad from Moscow On

Try the following

#include <stdio.h>

int main( void )
{
    int x = 0XABCDE98;

    x = ( ~0xF000 & x ) | 0x6000;

    printf( "%#X\n", x );

    return 0;
} 

The output is

0XABC6E98
0
AdminXVII On

n & 0x0000 "delete" the four last digits, so replace it with n & 0xFFF0FFF. That will keep all the digits except the fourth one (the 0).

0
Ali On

Lets have a look at what your program is doing:

(n & 0x0000)

Truth Table AND: Anything & 0 = 0, so the result of this is simply 0x0000

Truth Table OR: 0 | Anything = Anything

so now (0x0000) | 0x6000 = 0x6000

Effectively the line: n |= (n & 0X0000) | 0x6000;

simplifies to:

n |= 0x6000

The 4th last digit of n = D

Hex math: D | 6 = F hence your result 0xABCFE98

Solution? You need to try and 0 only the D digit first then OR with 0x6000 to set it to 6. There are many ways of doing this as suggested by other posters.

n = (n - 0xD000) | 0x6000 would also do the trick.