Skip to content

Instantly share code, notes, and snippets.

@alisinabh
Last active February 16, 2023 22:16
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alisinabh/2ab474860ca80904a7c6902289500fbc to your computer and use it in GitHub Desktop.
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]
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