Show return invalid value when used with unsafeCoerced value

I experimented with unsafeCoercewith Int8and Word8, and I found some amazing behavior (it doesn't matter to me).

Word8is an 8-bit unsigned number that ranges from 0 to 255. Int8is a signed 8-bit number that ranges from -128..127.

Since both of them are 8-bit numbers, I assumed that forcing one to the other would be safe and would simply return 8-bit values, as if it were signed / unsigned.

For example, unsafeCoerce (-1 :: Int8) :: Word8I would expect to get a value of Word8255 (since the bit representation of -1 in a signed int matches 255 in an unsigned int).

However, when I execute the enforcement, the Word8behavior is strange:

> GHCi, version 7.4.1: http://www.haskell.org/ghc/  :? for help
> import Data.Int
> import Data.Word
> import Unsafe.Coerce
> class ShowType a where typeName :: a -> String
> instance ShowType Int8 where typeName _ = "Int8"
> instance ShowType Word8 where typeName _ = "Word8"

> let x = unsafeCoerce (-1 :: Int8) :: Word8
> show x
"-1"
> typeName x
"Word8"
> show (x + 0)
"255"
> :t x
x :: Word8
> :t (x + 0)
(x + 0) :: Word8

, show x "-1" . map show [minBound..maxBound :: Word8], Word8 "-1". , 0 , ? , , Show - ShowType .

, fromIntegral (-1 :: Int8) :: Word8 , , 255, Show. Is/ no-op?

, , ghc . unsafeCoerce .

+5
2

@kosmikus, Int8 Int16 Int#, 32- 32- ( Word8 Word16 Word# ). GHC.Prim .

, , , :

> let x = unsafeCoerce (-1 :: Int8) :: Word8
> show x
"-1"

Show Word8

instance Show Word8 where
    showsPrec p x = showsPrec p (fromIntegral x :: Int)

fromIntegral - fromInteger . toInteger. toInteger Word8

toInteger (W8# x#)            = smallInteger (word2Int# x#)

smallInteger ( integer-gmp)

smallInteger :: Int# -> Integer
smallInteger i = S# i

word2Int# primop Word# -> Int# - reinterpret_cast<int> ++. , , -1 : .

, 0 x 255? Num Word8, :

(W8# x#) + (W8# y#)    = W8# (narrow8Word# (x# `plusWord#` y#))

, , narrow8Word# . :

> import GHC.Word
> import GHC.Prim
> case x of (W8# w) -> (W8# (narrow8Word# w))
255

. , 0 no-op - Word8, .

+10

, - , unsafeCoerce. , . , , Int8 , unsafeCoerce to Word8 , . fromIntegral .

Int8 Word8 fromIntegral movzbl ghc x86, no-op.

+4

All Articles