add_bits#

Feed an arbitrary number of bits into a Digest::SHA object.

Unlike add, this method is not restricted to whole bytes. It accepts two call forms:

  • One-argument form add_bits($bitstr) hashes a string of '0' and '1' characters — the hash takes one bit per character, so "01011010" adds exactly 8 bits of input.

  • Two-argument form add_bits($data, $numbits) hashes the first $numbits bits of the packed binary string $data. If $numbits exceeds 8 * length($data) it is capped at that value.

Most of the SHA standard is defined on bit-strings rather than byte-strings; this is the entry point for the bit-exact test vectors in FIPS 180-4.

Synopsis#

$sha->add_bits("11001010");          # 8 bits from ASCII 0/1 string
$sha->add_bits($packed, 13);         # first 13 bits of $packed

What you get back#

The receiver, for chaining.

Examples#

my $sha = Digest::SHA->new(256);
$sha->add_bits("01011010" x 8);   # 64 bits
print $sha->hexdigest;
## FIPS 180-4 1-bit test vector for SHA-1

my $sha = Digest::SHA->new(1);
$sha->add_bits("0");
print $sha->hexdigest;

## bb6b3e18f0115b9f9ededbb2a9cbfd2fe4c1a1a0
my $sha = Digest::SHA->new(256);
$sha->add_bits("\xab\xcd", 12);  # first 12 bits of 0xabcd

Edge cases#

  • The one-argument form ignores any character that is not '0' or '1'; an empty or all-non-bit string is a no-op.

  • In the two-argument form, passing a negative or zero bit count leaves the hash state untouched.

  • Called on a non-Digest::SHA object, returns undef.

Differences from upstream#

Fully compatible with upstream Digest::SHA 6.04.

See also#

  • add — standard byte-aligned input path; use it unless you truly have sub-byte data.

  • digest — finalises the running hash once input is complete.

  • addfile — byte-oriented file ingestion.