In MariaDB, BIT_LENGTH()
is a built in string function that returns the length of the given string argument in bits.
You provide the string as an argument when you call the function.
Syntax
The syntax goes like this:
BIT_LENGTH(str)
Where str
is the string.
Example
Here’s a simple example:
SELECT BIT_LENGTH('A');
Result:
+-----------------+ | BIT_LENGTH('A') | +-----------------+ | 8 | +-----------------+
We can see that the letter A is 8 bits long (i.e. 1 byte).
Here’s an example that uses characters that are longer than 1 byte:
SELECT
BIT_LENGTH('©'),
BIT_LENGTH('ไ'),
BIT_LENGTH('ม้');
Result:
+------------------+-------------------+----------------------+ | BIT_LENGTH('©') | BIT_LENGTH('ไ') | BIT_LENGTH('ม้') | +------------------+-------------------+----------------------+ | 16 | 24 | 48 | +------------------+-------------------+----------------------+
The second and third strings are Thai characters. The third string uses a diacritic mark, which ends up doubling the number of bits returned.
Here’s that character with and without the diacritic mark:
SELECT
BIT_LENGTH('ม้'),
BIT_LENGTH('ม');
Result:
+----------------------+-------------------+ | BIT_LENGTH('ม้') | BIT_LENGTH('ม') | +----------------------+-------------------+ | 48 | 24 | +----------------------+-------------------+
Wrong Argument Type
If the argument is not a string, it will be converted to string.
Example:
SELECT
BIT_LENGTH(1),
BIT_LENGTH(12),
BIT_LENGTH(123);
Result:
+---------------+----------------+-----------------+ | BIT_LENGTH(1) | BIT_LENGTH(12) | BIT_LENGTH(123) | +---------------+----------------+-----------------+ | 8 | 16 | 24 | +---------------+----------------+-----------------+
Null Arguments
Passing null
returns null
:
SELECT BIT_LENGTH(null);
Result:
+------------------+ | BIT_LENGTH(null) | +------------------+ | NULL | +------------------+
Missing Argument
Calling BIT_LENGTH()
without passing an argument results in an error:
SELECT BIT_LENGTH();
Result:
ERROR 1582 (42000): Incorrect parameter count in the call to native function 'BIT_LENGTH'