metro-man
metro-man

Reputation: 1793

What is the inverse of this bitwise shift?

The following statement gives me the value 1 (when I print it with %d). How can I do the opposite of this and give it 1 and it returns me 0x1234? Is this possible?

(0x1234 & 0xF000) >> 12

Upvotes: 1

Views: 1447

Answers (5)

Peter Cordes
Peter Cordes

Reputation: 364338

Your expression extracts bits [15:12] to the bottom of an integer. The rest of the bits are discarded: the right shift discarded the low 12. (Also the AND zeroed everything outside the 4-bit range.)

Obviously if you know what the low bits should be, you can put them back.

(v<<12) + 0x0234 = 0x1234

(or 0x0234 if bit 12 was 0. Or in general, 0x?234 for any 4-bit v. Each hex digit represents 4 bits of the binary integer.)

Upvotes: 0

phuclv
phuclv

Reputation: 41805

Shifting a number n bits to the right discards the right most n bits. The same thing happens during left shifting. ANDing a number with a mask also discards the bits which are 0 in the mask. Therefore there's no way to reconstruct the original number when many bits were lost

Upvotes: 1

No. 7892142
No. 7892142

Reputation: 121

To add onto fjardon's answer, the reason for the inability to go back is that, essentially, the byte shifted to the right are completely lost, you can not recover their values as they are not stored (at least not reliably).

In more mathematical terms, the right shift function is not injective and thus not bijective - more than one starting value can yield the same result. Hence, it's a one way train.

Upvotes: 2

Markus Dheus
Markus Dheus

Reputation: 576

As the expression extracts 4 bits (bits 12 to 15) from the original value (in this case 0x1234) there's no way to get the original value from the result of the expression.

Upvotes: 0

fjardon
fjardon

Reputation: 7996

(0x1FFF & 0xF000) >> 12

Will also gives 1. So the answer is no, you cannot go back to the original value

Upvotes: 3

Related Questions