Dmitro
Dmitro

Reputation: 1960

Concatenation bits in value

I need to concatenate bits, such as:

0x10 plus 0x12 = 0x1012
or
0x123 plus 0x4 = 0x1234

How I can do it, without string classes?

Upvotes: 2

Views: 109

Answers (2)

Spook
Spook

Reputation: 25927

You have to evaluate the rank of the rightmost value.

I believe, something like this should work:

// Returns rank of the value increased by one (except, when value == 0)
int rank(int value)
{
    int result = 0;
    while (value > 0)
    {
        value /= 16;
        result++;
    }

    return result;
}

int main(int argc, char * argv[])
{
    int left = 0x12;
    int right = 0x34;

    int sum = (left << (4 * rank(right))) + right;

    printf("%x\n", sum);
}

Upvotes: 3

Emanuele Paolini
Emanuele Paolini

Reputation: 10162

What you need is finding the position of the first hexadecimal digit in the second number, shift the first number to the left accordingly and then sum the numbers. To efficiently find the first digit of a binary number see here: http://en.wikipedia.org/wiki/Find_first_set Then make a modulo 4 operation to find the first hexadecimal digit.

Upvotes: 1

Related Questions