MariaDB BIT_LENGTH() Function

In MariaDB, BIT_LENGTH() is a built-in string function that returns the number of bits of the given string argument.

MariaDB BIT_LENGTH() Syntax

Here is the syntax of the MariaDB BIT_LENGTH() function:

BIT_LENGTH(str)

Parameters

str

Required. The string whose bit length needs to be calculated.

If a parameter is missing, MariaDB will report an error: ERROR 1582 (42000): Incorrect parameter count in the call to native function 'BIT_LENGTH'.

Return value

The MariaDB BIT_LENGTH() function returns the number of bits in a given string. The value returned by the BIT_LENGTH() function is 8 times the value returned by the LENGTH() function because 1 byte equals 8 bits.

If the parameter type is not a string type, the BIT_LENGTH() function will try to convert the parameter to a string.

It will return NULL if the argument str is NULL.

MariaDB BIT_LENGTH() Examples

Basic usages

This statement returns the bits of A and AB using BIT_LENGTH():

SELECT BIT_LENGTH('A'), BIT_LENGTH('AB');

Output:

+-----------------+------------------+
| BIT_LENGTH('A') | BIT_LENGTH('AB') |
+-----------------+------------------+
|               8 |               16 |
+-----------------+------------------+

We can see that the letter A has 8 bits (1 byte) and the AB has 16 bits (ie 2 bytes).

Here is an example using characters longer than 1 byte:

SELECT BIT_LENGTH('好');

Output:

+-------------------+
| BIT_LENGTH('好')  |
+-------------------+
|                24 |
+-------------------+

Invalid parameter type

If the argument is not a string, it will be converted to a string.

SELECT
  BIT_LENGTH(1),
  BIT_LENGTH(12),
  BIT_LENGTH(123);

Output:

+---------------+----------------+-----------------+
| BIT_LENGTH(1) | BIT_LENGTH(12) | BIT_LENGTH(123) |
+---------------+----------------+-----------------+
|             8 |             16 |              24 |
+---------------+----------------+-----------------+

Other Example

SELECT
    BIT_LENGTH('a'),
    BIT_LENGTH('string'),
    BIT_LENGTH(1),
    BIT_LENGTH(01),
    BIT_LENGTH('01'),
    BIT_LENGTH('你好'),
    BIT_LENGTH(NULL)\G

Output:

     BIT_LENGTH('a'): 8
BIT_LENGTH('string'): 48
       BIT_LENGTH(1): 8
      BIT_LENGTH(01): 8
    BIT_LENGTH('01'): 16
BIT_LENGTH('你好'): 48
    BIT_LENGTH(NULL): NULL

Note that the result returned by BIT_LENGTH(01) is not the same as BIT_LENGTH('01') because 01 is a number type, which will be converted first 1 and then executed BIT_LENGTH(1).

Conclusion

The MariaDB BIT_LENGTH() function returns the number of bits of the given string argument.