Home > Software design >  how to use bitwise operators to covert 32 bit decimal to hexadecimal in c?
how to use bitwise operators to covert 32 bit decimal to hexadecimal in c?

Time:09-23

I am supposed to write a function where a 32 bit decimal is converted to hexadecimal. But my function keeps outputting zero instead of the correct hexadecimal. I don't know what I'm doing wrong. Below is the code to my function.

input: 66

what the output should be: 42

what my code outputs: 0

uint32_t packed_bcd(uint32_t value) {
    uint32_t ones = 15;
    uint32_t mask = (ones >> 28);

    uint32_t numbers[8];
    numbers[0] = value & mask;

    for(int i = 1; i <= 7; i  ) {
        uint32_t mask_temp = (mask << (4 * i));
        numbers[i] = mask_temp & value;
    }

    for(int i = 7; i >= 0; i--) {
        numbers[i] = numbers[i] * pow(10, i);
    }

    int sum = 0;

    for(int i = 0; i < 8; i  ) {
        sum = sum   numbers[i];
    }

    return sum;
}

CodePudding user response:

BCD is not hex or normal binary.

uint32_t bcdtobin(uint32_t bcd)
{
    uint32_t result = 0;
    uint32_t mask = 1;

    while(bcd)
    {
        result  = (bcd & 0x0f) * mask;
        bcd >>= 4;
        mask *= 10;
    }
    return result;
}

uint32_t bintobcd(uint32_t bin)
{
    uint32_t result = 0;
    size_t remaining = 32;

    if(bin <= 99999999)
    {
        while(bin)
        {
            result >>= 4;
            result |= (bin % 10) << 28;
            bin /= 10;
            remaining -= 4;
        }
        result >>= remaining;
    }
    return result;
}

Using your example number:

int main(void)
{
    printf("%d\n", bintobcd(42));
    printf("%d\n", bcdtobin(66));
}

https://godbolt.org/z/9K48GEosv

  • Related