Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the size in bytes of an arbitrary integer

Tags:

erlang

elixir

Given an integer, 98749287 say, is there some built-in/libray function, either Erlang or Elixir, for getting the size in bytes?

To clarify, the minimum number of bytes used to represent the number in binary.

Seems simple, and have written a function using the "division by base" method and then counting bits, but after some hrs of searching docs havent found anything for what would seem useful to have.

like image 984
Englishbob Avatar asked Aug 26 '15 13:08

Englishbob


People also ask

How do you calculate the number of bytes in a number?

SORACOM uses the following for calculating byte conversion: 1 gigabyte (GB) = 1,024 megabytes (MB) 1 megabyte (MB) = 1,024 kilobytes (kB) 1 kilobyte (kB) = 1,024 bytes (B)

How many bytes are needed to store an integer?

1 Integers. Integers are commonly stored using a word of memory, which is 4 bytes or 32 bits, so integers from 0 up to 4,294,967,295 (232 - 1) can be stored.


2 Answers

If you have an unsigned integer, you can use the following snippet:

byte_size(binary:encode_unsigned(Integer))

Example:

1> byte_size(binary:encode_unsigned(3)).
1
2> byte_size(binary:encode_unsigned(256)).
2
3> byte_size(binary:encode_unsigned(98749287)).
4
like image 182
Adam Lindberg Avatar answered Sep 27 '22 01:09

Adam Lindberg


Try this expression:

Value = (... your input ...),
NumBytes = size(integer_to_binary(Value, 2) + 7) div 8.

Reference: http://www.erlang.org/doc/man/erlang.html#integer_to_binary-2

like image 34
Nayuki Avatar answered Sep 27 '22 01:09

Nayuki