Getting the n-th bit of a integer

Hello there,

Do you know any way to get the nth bit of an integer?

Obviously I can (and I do) use “Int.shift_right” and “mod 2”, but it is probably not the best way to do so, unless the compiler is able to handle such an operation well.

(Edited by hand, because the link was dropped during the e-mail transmission. Sorry)

Here is a nice reference (Not related to OCaml) that may help:

http://graphics.stanford.edu/~seander/bithacks.html

Best regards

1 Like

You should use land 1 instead of mod 2. Other than that, there is not much you can do to improve the generated code.

1 Like

Agreed. One reason is that x mod 2 can return -1 if x is negative…

If you want the bit as a Boolean instead of an integer, ((x lsr n) land 1) <> 0 should work fine.

1 Like

Prepare one mask value for each n and then bitwise-and the mask with your int.

Have you measured the relevance of further performance improvement? Can you provide the figures?

And what do you mean by ‘well’?