Wafer.Twiddles (wafer v1.1.1)

View Source

Handy functions for dealing with bits and bytes in the wild.

Summary

Functions

Set the specified bit to 0 within the byte.

Returns the number of 1's in byte.

Returns the number of 0's in byte.

Find all the 1 bits in byte and return a list of bit_numbers.

Find all the 0 bits in byte and return a list of bit_numbers.

Get the bit at the specified bit_number within byte.

Return a bit out of a binary as a boolean value.

Set a the specified bit_number to 1 within the byte.

Set the bit at the specified bit_number within the byte to the bit value.

Types

bit()

@type bit() :: 0..1

bit_number()

@type bit_number() :: 0..7

single_byte_binary()

@type single_byte_binary() :: <<_::8>>

Functions

clear_bit(byte, bit_number)

@spec clear_bit(byte() | single_byte_binary(), bit_number()) :: byte()

Set the specified bit to 0 within the byte.

Example

iex> clear_bit(3, 0)
2

iex> clear_bit(<<3>>, 0)
<<2>>

count_ones(byte)

@spec count_ones(byte() | single_byte_binary()) :: non_neg_integer()

Returns the number of 1's in byte.

Example

iex> count_ones(0x7f)
7

iex> count_ones(<<0x7F>>)
7

count_zeroes(byte)

@spec count_zeroes(byte() | single_byte_binary()) :: non_neg_integer()

Returns the number of 0's in byte.

Example

iex> count_zeroes(0x7f)
1

iex> count_zeroes(<<0x7F>>)
1

find_ones(byte)

@spec find_ones(byte() | single_byte_binary()) :: [non_neg_integer()]

Find all the 1 bits in byte and return a list of bit_numbers.

Example

iex> find_ones(0x0A)
[1, 3]

iex> find_ones(<<0x0A>>)
[1, 3]

find_zeroes(byte)

@spec find_zeroes(byte() | single_byte_binary()) :: [non_neg_integer()]

Find all the 0 bits in byte and return a list of bit_numbers.

Example

iex> find_zeroes(0xFA)
[0, 2]

iex> find_zeroes(<<0xFA>>)
[0, 2]

get_bit(byte, bit_number)

@spec get_bit(byte() | single_byte_binary(), bit_number()) :: bit()

Get the bit at the specified bit_number within byte.

Example

iex> get_bit(0x7f, 6)
1

iex> get_bit(<<0x7F>>, 6)
1

get_bool(byte, bit_number)

@spec get_bool(byte() | single_byte_binary(), bit_number()) :: boolean()

Return a bit out of a binary as a boolean value.

Example

iex> get_bool(0x7f, 6)
true

iex> get_bool(<<0x7F>>, 6)
true

is_bit(bit)

(macro)

is_bit_number(bit)

(macro)

is_byte(byte)

(macro)

set_bit(byte, bit_number)

@spec set_bit(byte() | single_byte_binary(), bit_number()) :: byte()

Set a the specified bit_number to 1 within the byte.

Example

iex> set_bit(0, 0)
1

iex> set_bit(<<0>>, 0)
<<1>>

set_bit(byte, bit_number, value)

@spec set_bit(byte() | single_byte_binary(), bit_number(), bit()) :: byte()

Set the bit at the specified bit_number within the byte to the bit value.

Example

iex> set_bit(0, 1, 1)
2

iex> set_bit(<<0>>, 1, 1)
<<2>>

iex> set_bit(0, 1, true)
2

iex> set_bit(<<0>>, 1, true)
<<2>>