Tuesday, 30 July 2019

How to Get the Number of Bits in a String in MySQL – BIT_LENGTH()

MySQL has a BIT_LENGTH() function that allows you to get the length of a string, measured in bits.
This function is similar to the LENGTH() function, which returns the length of a string in bytes. The same is true for the OCTET_LENGTH() function, which is a  synonym for the LENGTH() function.

Syntax

Here’s how the syntax goes:
BIT_LENGTH(str)
Where str is the string you need the bit length of.

Example – Single Character

Here’s an example using a character from the ASCII range:
SELECT BIT_LENGTH('A');
Result:
+-----------------+
| BIT_LENGTH('A') |
+-----------------+
|               8 |
+-----------------+
In this first example, we can see that the letter A has a length of 8 bits.

Example – Multiple Characters

Let’s add some more characters:
SELECT BIT_LENGTH('Anyone out there?');
Result:
+---------------------------------+
| BIT_LENGTH('Anyone out there?') |
+---------------------------------+
|                             136 |
+---------------------------------+

Example – Unicode Character

Here’s an example using the Euro sign. This is outside the ASCII range and it uses more storage space (i.e. more bits):
SELECT BIT_LENGTH('€');
Result:
+-------------------+
| BIT_LENGTH('€')   |
+-------------------+
|                24 |
+-------------------+

0 comments:

Post a Comment