jab
jab

Reputation: 5823

GIven two binary numbers, copy a subset from one to another

Let's say I have two binary numbers 00110010 and 11101110, and I would like to copy the last 4 values from second to the first to form a binary number of 00111110. Is there clean way to do this using bitwise operations on two bytes (or larger datatypes). Assume binary packed datatypes.

Also, is there a generic solution to this problem where any subset can be copied over. Let's say I wanted to copy some middle 3 bits from one number to another, what's the best way to accomplish this?

Upvotes: 3

Views: 337

Answers (2)

CS Pei
CS Pei

Reputation: 11047

you can try this

#include "stdio.h"

    int main()
    {
            int a = 0x52;
            int b = 0xee;

            int c = (a&0xF0)|(b&0x0F);


            printf(" %x %d\n",  c, c);

    }

a is 00110010, b is 11101110

Upvotes: 1

qaphla
qaphla

Reputation: 4733

If you have inputs x and y and want to copy a certain set of bits from x to y, say, the bits that are 1s in some variable m (a mask for the bits you want to copy), this can be done as follows:

int copy(int x, int y, int m) {
    return ((x & m) | (y & (~m)));
}

This will also work on things larger or smaller than ints, such as chars, shorts, longs, etc.

Taking (x & m) will give only the bits in x for which m has a 1 at that position, and (y & (~m)) will give only the bits in y for which m does not have a 1 at that position.

These are then ORed together with | to give the value whose bits in the positions where m has a 1 come from x, and whose bits in the positions where m has a 0 come from y.

Your particular case would have x = 0xee, y = 0x32, and m = 0xF.

Upvotes: 6

Related Questions