DEV Community

namuan
namuan

Posted on

Percent/URI Encoding - Step by Step example

Percent encoding is used to encode some reserved characters in the URI. See Wikipedia for more details.

As part of adding URL encoder in DevRider, I put together some notes which may be useful for others so publishing it here.

DevRider URL Encoder

Here we'll take a single character : and convert it to %3A which is the equivalent encoded character. This is a very simple example and don't cover unicode characters but it is similar in principle.

We start with finding the ASCII value of : which is 58.
See ASCII table for the mapping table.

Convert 58 to binary using Short division by Two with Reminder.
i.e. Divide the answer by 2 and keeping the reminder aside which will become the binary form.

58/2 = 29 => Reminder 0
29/2 = 14 => Reminder 1
14/2 = 7  => Reminder 0
7/2  = 3  => Reminder 1
3/2  = 1  => Reminder 1
1/2  = na => Reminder 1

So the binary form is 111010 if we line up all the reminders.
Padding the output will make it 00111010.

Next, we split the binary into two parts of 4 bits each.

0011 1010

Then using the following Hex table conversion, we map 0011 => 3 and 1010 to A which becomes 3A.

Decimal Binary Hex
1 0001 1
2 0010 2
3 0011 3
4 0100 4
5 0101 5
6 0110 6
7 0111 7
8 1000 8
9 1001 9
10 1010 A
11 1011 B
12 1100 C
13 1101 D
14 1110 E
15 1111 F

The final part is to prefix it with % (which is the escape character) making it %3A which is the output we are expecting. 🎉

Top comments (0)