Haskell function seems to be limiting integer length - i thought it used bignums?
Asked Answered
D

1

5

i've got a short haskell function here that is supposed to convert "ABCDEF" into 0x41,0x42,0x43,0x44,0x45,0x46 (their ascii values), then multiply them so it becomes 0x4142,4344,4546 but it seems to be limiting integer length - i thought haskell used arbitrary bignums?

The last line of the code works fine, which puzzles me

Any ideas? Thanks a lot

import Data.Char
import Numeric

strToHex2 (h:[]) = ord h
strToHex2 (h:t) = (ord h) + ((strToHex2 t) * 256)
strToHex s = strToHex2 (reverse s)

main = do
  print(strToHex "ABCDEF")
  print ((((((((0x41*256+0x42)*256)+0x43)*256)+0x44)*256)+0x45)*256+0x46)

The output is:

1128547654      <- limited to 32 bits for some reason?
71752852194630  <- that's fine
Domesticity answered 16/7, 2010 at 2:40 Comment(2)
See also https://mcmap.net/q/127190/-what-is-the-difference-between-int-and-integerRostand
Types are your friend. Add type signatures, and it is clear what is going on!Easing
C
10

Your problem is that ord returns an Int, which is fixed-width. You want toInteger $ ord h.

Contorted answered 16/7, 2010 at 2:47 Comment(1)
So there's a difference between an Int and an Integer?Domesticity

© 2022 - 2024 — McMap. All rights reserved.