A
A
avion2018-09-25 22:31:18
C++ / C#
avion, 2018-09-25 22:31:18

Bit representation of numbers in c++?

Hello, how to solve this problem in C++:
1. Delete the i-th bit from the binary representation of a positive integer (lower bits of the i-th remain in place, the older bits are shifted one bit to the right).

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-09-25
@avion123678

You make two bit masks - all ones for the lower bits (before the cut bit), all ones for the high bits (after the cut bit). Apply both masks to the number, shift the most significant digits by one to the right, combine the resulting numbers:

int value = // ваше число, чему-то там равно, вам виднее

int bit = // номер вырезаемого бита, тоже вам виднее

int maskLower = 0;
for (int i = 0; i < bit - 1; i++) {
  maskLower |= 1 << i;
}
int maskUpper = ~maskLower;

value = ((value >> 1) & maskUpper) | (value & maskLower);

UPD. The loop for creating the mask is of course superfluous, as res2001 rightly noted in the comments .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question