RV1DEN
RV1DEN

Reputation: 23

How to insert bit into long number

There is a sequence of bits. Is it possible to insert the bit in particular position between others bits?

For example:

  1. We have some number long n, which looks in binary like 10010;
  2. We have some method long insert(long numb, position);
  3. After using insert(n, 2) we must get following sequence of bits:101010

Thank you for answering!

Upvotes: 2

Views: 732

Answers (2)

stdout
stdout

Reputation: 2651

I would shift the number 'n' left by 1 bit. Then I would create a long l1 with value 1, shift it left by "positon" bits, and finally OR l1 and n.

Also, depending on your use case, it might be necessary to save/keep the most significant bit before it gets shifted out (or the carried out bit).

Upvotes: 0

xingbin
xingbin

Reputation: 28279

  1. convert long to binary String
  2. insert bit at specified position
  3. then convert it back to long

public long insert(long number, int position) {
    String longString = Long.toBinaryString(number);
    longString = longString.substring(0, position) + "1" + longString.substring(position);
    return Long.parseLong(longString, 2);
}

Upvotes: 3

Related Questions