Skip to content

Add fromBitString #4

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions src/Int64.elm
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ module Int64 exposing
, signedCompare, unsignedCompare
, toSignedString, toUnsignedString
, toHex, toBitString
, fromBitString
, decoder, encoder
, toByteValues, toBits
)
Expand Down Expand Up @@ -41,6 +42,11 @@ This is a low-level package focussed on speed. The 64-bit integers are represent
@docs toHex, toBitString


## Conversion from String

@docs fromBitString


## Conversion to Bytes

@docs decoder, encoder
Expand Down Expand Up @@ -493,6 +499,65 @@ toBitString input =
""


{- Create an `Int64` from a string of `0`s and `1`s in big-endian order.

fromBitString "101"
--> fromInt 5
-}
fromBitString : String -> Maybe Int64
fromBitString string =
string
|> bitsFromString
|> Maybe.map fromBits


fromBits : List Bool -> Int64
fromBits bits =
Int64
(Bitwise.shiftRightZfBy 0 <| fromBits32 <| List.drop 32 bits)
(Bitwise.shiftRightZfBy 0 <| fromBits32 <| List.take 32 bits)


fromBits32 : List Bool -> Int
fromBits32 =
Tuple.second << List.foldl
(\bit (i, accum) ->
( i + 1
, if bit
then
Bitwise.or
accum
(Bitwise.shiftLeftBy i 1)
else
accum
)
)
(0, 0)


-- Lowest bit is first
bitsFromString : String -> Maybe (List Bool)
bitsFromString =
String.foldl
(\b maybeAccum ->
case maybeAccum of
Nothing ->
Nothing

Just accum ->
case b of
'1' ->
Just <| True :: accum

'0' ->
Just <| False :: accum

_ ->
Nothing
)
(Just [])


{-| Interpret a `Int64` as an unsigned integer, and give its string representation

toSignedString (fromInt 10)
Expand Down
9 changes: 9 additions & 0 deletions tests/TestInt64.elm
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,15 @@ fuzzTests =
|> Int64.fromInt
|> Int64.toSignedString
|> Expect.equal (String.fromInt a)
, fuzz Fuzz.int "binary string conversion" <|
\a ->
let
int64 = Int64.fromInt a
in
int64
|> Int64.toBitString
|> Int64.fromBitString
|> Expect.equal (Just int64)
, fuzz (Fuzz.map abs Fuzz.int) "from positive in to unsigned string" <|
\a ->
a
Expand Down