K
K
kykyryky2015-05-11 21:04:04
Programming
kykyryky, 2015-05-11 21:04:04

How to "insert" bits into a number?

Let's say there is a number:
0000 0000 0100 0100
Variable 2 bytes.
Suppose we need to "insert" zero in the last 8 bits so that it is in positions with numbers equal to powers of two. We have the first 8 bits in reserve, because the result will "increase" by 4 bits.
That is, as a result, you should get:
0000 00 0 0 100 0 0100
Figuratively speaking, somehow you need to shift some of the bits to the left several times, thereby creating new bits in the right positions.
How to implement? give a hint.
Upd C language

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2015-05-11
@kykyryky

Depends on the programming language. For example in C
y = ((x&0xF0)<<4)|((X&0x0E)<<3)|((x&1)<<2);

M
Mrrl, 2015-05-12
@Mrl

If you need to do as in your example (i.e. insert bits 2048,1024,256,16), then like this:
But no one numbers the beats like that. Usually they are numbered starting from the youngest - sometimes it is considered as zero, sometimes as the first.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question