haskell - Interpreting unsigned integers as signed while widening -
suppose i've got lot of values of type word8
, word16
, , word32
lying around. want widen them, interpreting signed , unsigned, can store them in [int64]
. know can write following function, first argument specifies whether want interpret word8
signed or not:
convert8 :: bool -> word8 -> int64 convert8 false = fromintegral convert8 true = fromintegral (fromintegral :: int8)
this gives me result want:
*main> convert8 false 128 128 *main> convert8 true 128 -128
the double fromintegral
feels inelegant me, though. there nicer way "interpret word
signed integer , stick in bigger int
"?
from recall, ghc stores integers 1 machine word. (in other words, 32-bit ghc stores integers 32 bits. 64-bit ghc stores them 64 bits.) if request 8-bit integer, stores 32 bits anyway, uses first 8 bits.
because of this, i'm sure widening or narrowing using fromintegral
no-op @ run-time; change type signature, no run-time cost. (converting unsigned signed might doing sign extension, however. i'm not sure how part works. it's still 1 machine instruction though.)
in short, think double fromintegral
best way this. manually implement sign extension yourself, built-in machine instruction doing faster.
Comments
Post a Comment