Reputation: 905
In erlang, how come byte size of huge number represented as binary is one? I'd thought it should be more?
byte_size(<<9999999999994345345645252525254524352425252525245425422222222222222222524524352>>).
1
Upvotes: 2
Views: 407
Reputation: 3996
In erlang this data type is a binary. Binary is a sequence of 8-bit (bytes) elements.
You entered only one value into this binary so the resulted value is actually the modulo 256 of this value. If you'll enter only the binary in the shell you'll get:
1> <<9999999999994345345645252525254524352425252525245425422222222222222222524524352>>.
<<"@">>
@
ASCII value is 64. Which means that this_long_num modulo 256 = 64.
As you might have already understood, this means that it represents only 1 byte - so this is the reason that the byte_size/1
of this binary is 1.
Upvotes: 3
Reputation: 12547
If you want to convert arbitrary integer to its binary representation, you should use binary:encode_unsigned
7> byte_size(binary:encode_unsigned(9999999999994345345645252525254524352425252525245425422222222222222222524524352)).
33
encode_unsigned(Unsigned) -> binary()
Types:
Unsigned = integer() >= 0
Same asencode_unsigned(Unsigned, big)
.encode_unsigned(Unsigned, Endianness) -> binary()
Types:
Unsigned = integer() >= 0 Endianness = big | little
Converts a positive integer to the smallest possible representation in a binary digit representation, either big endian or little endian.
Upvotes: 3
Reputation: 20024
You're not specifying an integer size, so the value narrows to just a single byte, as you can see using the Erlang shell:
1> <<9999999999994345345645252525254524352425252525245425422222222222222222524524352>>.
<<"@">>
If you specify the proper size, which appears to be 263 bits, you get the right answer:
2> byte_size(<<9999999999994345345645252525254524352425252525245425422222222222222222524524352:263>>).
33
Upvotes: 4