Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I bit-convert between Int and Word quickly?

The Haskell base documentation says that "A Word is an unsigned integral type, with the same size as Int."

How can I take an Int and cast its bit representation to a Word, so I get a Word value with the same bit representation as the original Int (even though the number values they represent will be different)?

I can't use fromIntegral because that will change the bit representation.

I could loop through the bits with the Bits class, but I suspect that will be very slow - and I don't need to do any kind of bit manipulation. I want some kind of function that will be compiled down to a no-op (or close to it), because no conversion is done.

Motivation

I want to use IntSet as a fast integer set implementation - however, what I really want to store in it are Words. I feel that I could create a WordSet which is backed by an IntSet, by converting between them quickly. The trouble is, I don't want to convert by value, because I don't want to truncate the top half of Word values: I just want to keep the bit representation the same.

like image 720
Isaac van Bakel Avatar asked Sep 24 '20 10:09

Isaac van Bakel


1 Answers

int2Word#/word2Int# in GHC.Prim perform bit casting. You can implement wrapper functions which cast between boxed Int/Word using them easily.

like image 70
Cheng Shao Avatar answered Oct 16 '22 09:10

Cheng Shao