1

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
metro-man
  • 1,763
  • 2
  • 15
  • 28
  • By the answers you already know that the only way to "go back" to the original value, is to preserve it by storing it in some variable. Use a temporary variable to do your bitwise manipulations. Think about a practical application. You can do this to determine what subnet a given address belongs to. You do this by "masking" the address. The result is the subnet (one value). But how can you get a specific address from a subnet? You can't. The result could be any of all the possible addresses that belong to it. – hfontanez Apr 02 '19 at 17:14

5 Answers5

3
(0x1FFF & 0xF000) >> 12

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

fjardon
  • 7,921
  • 22
  • 31
2

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.

No. 7892142
  • 121
  • 4
1

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

phuclv
  • 37,963
  • 15
  • 156
  • 475
0

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.

Markus Dheus
  • 576
  • 2
  • 8
0

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.)

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847