Jump to content

Recommended Posts

Posted

Oi, eu sou novo programando em haskell  e estou com problema em fazer a conversão de binário para decimal.

Já consegui fazer de decimal para binário como podem ver abaixo:

decpbin :: Int -> String
decpbin 0 = "0"
decpbin 1 = "1"
decpbin n = decpbin(n `div` 2) ++ show(n `mod` 2)

Se poderem ajudar agradeço.

  • 3 weeks later...
Posted (edited)
Em 18/10/2016 às 15:37, jota.fullstack disse:

Uma solução rápida:


fromBinary :: String -> Int
fromBinary str = sum $ zipWith toDec (reverse str) [0 .. length str]
  where toDec a b = digitToInt a * (2 ^ b)

Espero ter ajudado.

 

Esta solução, para além de introduzir funções de ordem superior, que julgo já serem avançadas dado o exercício típico de iniciante em Haskell, não me parece nada rápida. Já viste quantas vezes estás a percorrer a string inicial? Penso que o que se pretende é algo mais básico e até mais rápido. Vou deixar aqui visto que já passaram 15 dias.

bin2dec :: String -> Int
bin2dec "" = 0
bin2dec s = let l = length s - 1
            in bin2dec' s l
                   
bin2dec' :: String -> Int -> Int
bin2dec' "" _ = 0
bin2dec' (x:xs) l = (toInt x)*(2^l) + bin2dec' xs (l-1)
	
toInt :: Char -> Int
toInt c = ord c - ord '0'
Edited by Baderous

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.