Reputation: 23
There is a sequence of bits. Is it possible to insert the bit in particular position between others bits?
For example:
long n
, which looks in binary like 10010
;long insert(long numb, position)
;insert(n, 2)
we must get following sequence of bits:101010 Thank you for answering!
Upvotes: 2
Views: 732
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
Reputation: 28279
long
to binary String
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