-1

How would i extract bits of a hex number in crystal lang which is mostly like ruby because i am able to extract a byte but i cannot extract 4 bits of one cause that is what i need to do here is what I want to extract.
0x0312FCFC
------^^(the 1 and 2)
How would i extract those 2 here is my code to extract the first one and the last 4

op = ((x.to_i(16)) >> 24) & 0xff
im = (x.to_i(16)) & 0xffff

What i have tried was

a1 = ((x.to_i(16)) >> 16) & 0xf0
a2 = ((x.to_i(16)) >> 16) & 0x0f
xd-sudo
  • 1
  • 1

1 Answers1

2

First, shift the number of bits that you need to the right. In your example, it should be 16 (4*4, as you want to skip the last 4 hex chars FCFC) and 20 (5*4, skipping 2FCFC). Then mask the last byte (... & 0xF).

x = 0x0312FCFC
a = (x >> 16) & 0xF   # a = 2
b = (x >> 20) & 0xF   # b = 1

And yes, the code is identical in Ruby and Crystal.

Philipp Claßen
  • 41,306
  • 31
  • 146
  • 239