Brasilex.Boleto.Checksum.Mod11 (Brasilex v0.3.0)

Copy Markdown View Source

Implements the Modulo 11 check digit algorithm as defined by FEBRABAN.

Used to validate the general barcode check digit in Brazilian boletos.

Algorithm

  1. Starting from right to left, multiply each digit by weights 2-9 cyclically
  2. Sum all products
  3. Calculate: 11 - (sum mod 11)
  4. Special cases depend on boleto type:
    • Banking: 0, 1, 10, 11 → 1
    • Convenio: 0, 10, 11 → 0

Summary

Functions

Calculates the Modulo 11 check digit for banking boletos.

Calculates the Modulo 11 check digit for convenio boletos.

Validates that a check digit matches the expected value for banking boletos.

Validates that a check digit matches the expected value for convenio boletos.

Functions

calculate(digits)

@spec calculate(String.t()) :: non_neg_integer()

Calculates the Modulo 11 check digit for banking boletos.

Maps special cases 0, 1, 10, 11 → 1.

Examples

# All zeros yields sum=0, so 11-(0 mod 11)=11 -> special case returns 1
iex> Brasilex.Boleto.Checksum.Mod11.calculate("0000000000000000000000000000000000000000000")
1

calculate_convenio(digits)

@spec calculate_convenio(String.t()) :: non_neg_integer()

Calculates the Modulo 11 check digit for convenio boletos.

Maps special cases 0, 10, 11 → 0 (different from banking).

valid?(digits, expected_check)

@spec valid?(String.t(), non_neg_integer() | String.t()) :: boolean()

Validates that a check digit matches the expected value for banking boletos.

Examples

iex> zeros = String.duplicate("0", 43)
iex> Brasilex.Boleto.Checksum.Mod11.valid?(zeros, 1)
true

iex> zeros = String.duplicate("0", 43)
iex> Brasilex.Boleto.Checksum.Mod11.valid?(zeros, "1")
true

iex> zeros = String.duplicate("0", 43)
iex> Brasilex.Boleto.Checksum.Mod11.valid?(zeros, 9)
false

valid_convenio?(digits, expected_check)

@spec valid_convenio?(String.t(), non_neg_integer() | String.t()) :: boolean()

Validates that a check digit matches the expected value for convenio boletos.

Uses convenio variant of Mod11 (maps 0, 10, 11 → 0).