# Haskell Program to get total Bits Required for the Given Number using Library Function



## Output

[1 of 1] Compiling Main             ( main.hs, main.o )
The number 42 requires 64 bits to represent.


## Example 2

In this example, the total bits required for the given number is computed using ceiling and logBase function.

import Numeric.Natural

bitsRequired :: Integer -> Int
bitsRequired n = ceiling (logBase 2 (fromIntegral (abs n) + 1))

main :: IO ()
main = do
let x = 42

bits = bitsRequired x
putStrLn $"The number " ++ show x ++ " requires " ++ show bits ++ " bits to represent."  ## Output [1 of 1] Compiling Main ( main.hs, main.o ) Linking main ... The number 42 requires 6 bits to represent.  ## Example 3 In this example, the total bits required for the given number is computed using length and showIntAtBase function. import Numeric (showIntAtBase) import Data.Char (intToDigit) bitsRequired :: Integer -> Int bitsRequired n = length$ showIntAtBase 2 intToDigit (abs n) ""

main :: IO ()
main = do
let x = 42
bits = bitsRequired x
putStrLn \$ "The number " ++ show x ++ " requires " ++ show bits ++ " bits to represent."


## Output

[1 of 1] Compiling Main             ( main.hs, main.o )
The number 42 requires 6 bits to represent.


## Conclusion

The total number of bits required by a number depends on the number itself and the number of bits used to represent it. For example, if we're using 32-bit integers, then the maximum value that can be represented is 2^31 - 1 = 2147483647, which requires 31 bits to represent. If we're using 64-bit integers, then the maximum value that can be represented is 2^63 - 1 = 9223372036854775807, which requires 63 bits to represent. We can use certain functions to compute the same in Haskell.

Updated on: 28-Mar-2023

30 Views