F
F
Flaker2015-09-05 20:26:20
Programming
Flaker, 2015-09-05 20:26:20

How to convert certain bits in a number?

I do not understand how to convert the given bits in a number that is not known in advance.
For example, the number 115 in binary form is 1110011.
We want to make 3 bits to the left of the second position as ones.
To do this, we must apply the OR operation: res = 1110011 | 0011100
But if the number itself, position and number of bits are set dynamically, how to select numbers?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Mrrl, 2015-09-05
@Flaker

If the position number is pos, the number of digits is len, and the number to be changed is x, then the answer is
x | (((1 << len) - 1) << pos)

A
Armenian Radio, 2015-09-05
@gbg

Generate numbers that correspond to the desired ones in the binary system.
For example, to set 1 to the nth digit of a number, you can use shift:
a = 1 << n;

S
slinkinone, 2015-09-05
@slinkinone

You can take a unit (var1 = 00000001), apply | (bitwise or), then we get 1 in the first bit, bitwise left shift to var1 - we get (00000010) and also apply | to the correct number.
Very good article:
chipenable.ru/index.php/programming-avr/item/4-uch...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question