関数型プログラミング言語Haskell Part9at TECH関数型プログラミング言語Haskell Part9 - 暇つぶし2ch■コピペモード□スレを通常表示□オプションモード□このスレッドのURL■項目テキスト800:デフォルトの名無しさん 08/10/02 01:06:55 >>799 問題ある >>797は、バイナリモードで開いた上でgetContentsすればいい、という意味で言った >>798 確かにそうだな ちゃんとテストしてないけど一応こんなんでいけるみたいだ import Data.Bits import Data.Word w32ToFloat :: Word32 -> Float w32ToFloat w | ep == 255 && sf /= 0 = 0 / 0 | sf == 255 = sign / 0 | sf == 0 && ep == 0 = sign * 0 | otherwise = sign * encodeFloat r e where sn = shiftR w 31 ep = shiftR w 23 .&. 0xff sf = w .&. 0x7fffff sign = if sn == 1 then -1 else 1 e = fromIntegral ep - 127 - 23 r = fromIntegral sf + 0x800000 801:デフォルトの名無しさん 08/10/02 01:37:29 バイト列をFloatとして解釈させたいわけだから、 必要なのは Word32 -> Float じゃなくて [Word8] -> Float なんじゃなかろうか。 というわけでPtr経由だけど書いてみた。 import Foreign fromBytes :: Storable a => [Word8] -> a fromBytes bs = unsafePerformIO $ allocaArray (length bs) $ \ p -> pokeArray p bs >> peek (castPtr p) toBytes :: Storable a => a -> [Word8] toBytes x = unsafePerformIO $ alloca $ \ p -> poke p x >> peekArray (sizeOf x) (castPtr p) toBytes (0.5 :: Float) => [0,0,0,63] fromBytes [0,0,0,63] :: Float => 0.5 次ページ最新レス表示レスジャンプ類似スレ一覧スレッドの検索話題のニュースおまかせリストオプションしおりを挟むスレッドに書込スレッドの一覧暇つぶし2ch