core :: Text :: binarydigest_to_bytes
Bytes
by reading 0 and 1.assert "1010101100001101".binarydigest_to_bytes.hexdigest == "AB0D"
Note that characters that are neither 0 or 1 are just ignored.
assert "a1B01 010\n1100あ001101".binarydigest_to_bytes.hexdigest == "AB0D"
assert "hello".binarydigest_to_bytes.is_empty
When the number of bits is not divisible by 8, then leading 0 are implicitly considered to fill the left byte (the most significant one).
assert "1".binarydigest_to_bytes.hexdigest == "01"
assert "1111111".binarydigest_to_bytes.hexdigest == "7F"
assert "1000110100".binarydigest_to_bytes.hexdigest == "0234"
Bytes::binarydigest
is a loosely reverse method since its
results contain only 1 and 0 by blocks of 8.
assert "1010101100001101".binarydigest_to_bytes.binarydigest == "1010101100001101"
assert "1".binarydigest_to_bytes.binarydigest == "00000001"
# Return a `Bytes` by reading 0 and 1.
#
# assert "1010101100001101".binarydigest_to_bytes.hexdigest == "AB0D"
#
# Note that characters that are neither 0 or 1 are just ignored.
#
# assert "a1B01 010\n1100あ001101".binarydigest_to_bytes.hexdigest == "AB0D"
# assert "hello".binarydigest_to_bytes.is_empty
#
# When the number of bits is not divisible by 8, then leading 0 are
# implicitly considered to fill the left byte (the most significant one).
#
# assert "1".binarydigest_to_bytes.hexdigest == "01"
# assert "1111111".binarydigest_to_bytes.hexdigest == "7F"
# assert "1000110100".binarydigest_to_bytes.hexdigest == "0234"
#
# `Bytes::binarydigest` is a loosely reverse method since its
# results contain only 1 and 0 by blocks of 8.
#
# assert "1010101100001101".binarydigest_to_bytes.binarydigest == "1010101100001101"
# assert "1".binarydigest_to_bytes.binarydigest == "00000001"
fun binarydigest_to_bytes: Bytes
do
var b = bytes
var max = byte_length
# Count bits
var bitlen = 0
var pos = 0
while pos < max do
var c = b[pos]
pos += 1
if c == u'0' or c == u'1' then bitlen += 1
end
# Allocate (and take care of the padding)
var ret = new Bytes.with_capacity((bitlen+7) / 8)
var i = (bitlen+7) % 8 # current bit (7th=128, 0th=1)
var byte = 0 # current accumulated byte value
pos = 0
while pos < max do
var c = b[pos]
pos += 1
if c == u'0' then
byte = byte << 1
else if c == u'1' then
byte = byte << 1 | 1
else
continue
end
i -= 1
if i < 0 then
# Last bit known: store and restart
ret.add byte
i = 7
byte = 0
end
end
return ret
end
lib/core/bytes.nit:950,2--1012,4