Last active
February 16, 2023 22:16
-
-
Save alisinabh/2ab474860ca80904a7c6902289500fbc to your computer and use it in GitHub Desktop.
Elixir convert binary (byte array) to signed Int32 with pattern matching and vice versa [DEPRECARED - just use whats inside the functions]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule ZigorProxy.BitConverter do | |
@moduledoc """ | |
This module handles standard binary operations. | |
Converting binaries to and from general data types. | |
""" | |
require Logger | |
@doc """ | |
Converts binary of 4 bytes into an signed integer. | |
First byte is considered as signature of number. | |
## Examples | |
iex> ZigorProxy.BitConverter.get_int32(<<255,255,255,255>>) | |
-1 | |
iex> ZigorProxy.BitConverter.get_int32(<<10,0,0,0>>) | |
10 | |
""" | |
def get_int32(<<num::little-signed-integer-size(32)>>) do | |
num | |
end | |
@doc """ | |
Converts a number into binary. | |
this function handles negative and positive numbers. | |
## Examples | |
iex> ZigorProxy.BitConverter.int32_bytes(-1) | |
<<255,255,255,255>> | |
iex> ZigorProxy.BitConverter.int32_bytes(5) | |
<<5,0,0,0>> | |
""" | |
def int32_bytes(number) do | |
<<number::little-signed-32>> | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment