# Working With Number – Converting Binary And Hexadecimal – Ruby

In programming, we most often have to deal with numbers. There are four numbering systems that are commonly use in the programming world, and they are binary, octal, hexadecimal and decimal. Often time we have to convert one numbering system to another. By understanding the properties of each numbering system, its can help us efficient our programming protocol when it’s come to working between two or more numbering systems. This article is a tutorial on how to convert numbers between the binary numbering system and the hexadecimal numbering system. The source code for this tutorial was written in Ruby. The method of this article would represent and store binary numbers or hexadecimal numbers in strings format.

A hexadecimal numbering system is a base sixteen numbering system. A base sixteen numbering system is a numbering system that uses sixteen symbols to represent values. Hexadecimal numbering system uses zero to nine and A to F to represents values. Zero being the lowest and F being the highest.

A binary numbering system is a base two numbering system. A base two numbering system is a numbering system that uses two symbols to represents values. Binary numbering system uses zero and one to represents values. Zero being the lowest and one is the highest.

When working with many programming languages, I noticed that for mathematical equations, we are being limited to how much storage one single number can be stored in memory. For example when convert hexadecimal to binary in PHP, you are limited to a forty characters string length at the time of this writing. Anything above forty characters will produce an all zero result value. Nevertheless, sometimes we have to work with an application that requires encoding in hexadecimal base value and we simply can’t use the PHP built in function because the hexadecimal string would most likely be longer than forty digits in length. This two methods for converting between binary base and hexadecimal base numbering system within this tutorial only face one limitation, and that is how much RAM the computer system have or is the data larger than the maximum free space on the disk drive. As in short with these methods you can convert very large numbers that can be millions of digits or more in length.

### How To Convert Binary To Hexadecimal

When converting between binary numbers to hexadecimal numbers we have two methods of doing so. The first method is to convert each four digits of the binary numbers to a decimal value and then convert that decimal value to a hexadecimal value. The table below will illustrate the value of each numbering system, binary, hexadecimal and decimal.

Values of Numbering System
Binary
Decimal
000000
000111
001022
001133
010044
010155
011066
011177
100088
100199
1010A10
1011B11
1100C12
1101D13
1110E14
1111F15

When looking at the table above we can then apply the formula below to get the hexadecimal value for any binary number.

```Formula:
Step 1: Add zero to the leftmost of the binary string until the string length is divisible by four.
Step 2: Starting from the most left of the binary string, convert a four digits block of binary to a decimal value.
Step 3: If the converted digit is higher than nine, convert the value to a corresponding letter.
10 = A, 11 = B, 12 = C, 13 = D, 14 = E, 15 = F.
Step 4: Store the converted digit starting from left to right in a string.
Step 5: Repeat the previous steps, starting from step two until the whole binary string is converted.
Answer: Once completed all the previous step, the converted string of hexadecimal digits, is the hexadecimal value of the binary string.

Example: Convert 1 1100 0011 1110 1101 binary value to hexadecimal value.
Step 1:       0001 1100 0011 1110 1101
Step 2:         1   12   3    14  13
Step 3:         1   C    3    E   D
Answer:         1C3ED is the hexadecimal value of 1 1100 0011 1110 1101 binary value.
```

When putting the above formula into a programming perspective. The first thing that a program have to execute first before anything is to check for the length of the input binary string. If the length of the binary string is not divisible by four, zero would have to be appended to the beginning of the string until the string length is divisible by four. To achieve this we can use a while loop that will execute if the length of the string is not divisible by four. Each time the while loop is executed, a zero is appended to the beginning of the binary string.

```
while( _input.length % 4 != 0 ) do
_input = "0" + _input
end
```

When reading the binary string for conversion, the protocol is to collect and convert four digits of binary at a time. Thus every time the program read the string, it has to move by four positions. This is easy enough since we are reading the string forward from the zero position. We can just have a while loop with an index count. Each time the loop executed, the index count is increased by four. The loop will execute as long as our index count is below the total length of the binary string.

Besides that, we have to declare a map variable that would store the hexadecimal characters that corresponding to the decimal value of “10” to “15”. When the converted decimal is larger than nine, we would use this map to convert the decimal value that we just converted from the binary value to its corresponding hexadecimal value. The below code show that variable i is our index count and the map variable store the corresponding hexadecimal value in the event where our converted decimal is larger than nine.

```_map = {10 => "A", 11 => "B", 12 => "C", 13 => "D", 14 => "E", 15 => "F"}
_i = 0
_output = ""

while( _i < _input.length) do
_temp = 0
_temp = _input[_i + 3] == "0"? _temp : _temp + 1
_temp = _input[_i + 2] == "0"? _temp : _temp + 2
_temp = _input[_i + 1] == "0"? _temp : _temp + 4
_temp = _input[_i] == "0"? _temp : _temp + 8
_output = _temp > 9? _output + _map[_temp] : _output + _temp.to_s
_i = _i + 4
end
```

The second method for convert a binary value to a hexadecimal value is by converting each four digits of binary directly into its corresponding hexadecimal value using the Values of Numbering System table above. In my opinion, method two is actually the best method in programming for converting a binary value to a hexadecimal value. With this method, we do not need to execute any mathematical equation. Thus, it’s would reduce the amount of time needed for execution. The second method can simply be explained as a method to compare the value of two strings. Method two can be explained below.

```Method 2:
Step 1: Add zero to the left of the binary string until its length is divisible by four. If the binary string's length is already divisible by for skip this step.
Step 2: Make a table that maps the hexadecimal value for binary digit from 0000 to 1111.
Step 2: Starting from left to right of the binary string, convert each four digits block to their corresponding hexadecimal value.
Step 3: Store the order of each hexadecimal digit in a string starting the same order as reading the binary string.
Answer: After every four digits binary block in the binary string is converted to a hexadecimal value.

Example:    Convert  11  1101  1001  1001  1110  1010 to hexa decimal.
Step 1:            0011  1101  1001  1001  1110  1010
Step 2:             3      D     9     9     E     A
Answer:             3D99EA is the hexadecimal value of 0011 1101 1001 1001 1110 1010 binary value.
```

Putting the above formula into a programming context, our binary to hexadecimal converter would need a map that maps every possible value of all the four digits binary block from “0000” to “1111” to their corresponding hexadecimal value. If the programming language we are dealing with has the capability of storing information within an object or a similar architecture, we can simply declare an object style variable. Objects are variables that can store information within its key, as a key to value(s) pair. In Ruby, a Hash type variable provides the similar architecture of an Object.

If the programming language we are working with does not have a built-in object architecture, we can replace the object declaration with many if and if else conditional code block or we can create a string with both the binary values and their hexadecimal value. We can then manipulate the string to get either value, binary or hexadecimal. For an example of how to manipulate values that are stored in a string using a defined pattern, you can refer to my other article on converting between hexadecimal and binary written for Java and Groovy.

As for converting we will read through the binary string from position zero and we are moving by four positions at a time until we reach four positions before the end of the string. Notice that, if the string is length 20 and the index was set to a zero value, and a value of four would be added to the index after every loop execution, and the loop was set to execute only if the index value is less than the string length value, our loop will execute with the index being the following values 0,4,8,12 and 16 but not 20 . Each time in the loop, we would get four binary digits starting at our current position. We then use that string and match it to our map to get the corresponding hexadecimal value, then we would append the hexadecimal value to the end of our output string. Similar to method one, we have to make the binary string length divisible by four by append zero(s) to the left of the string if the string length is not equally dividable by four.

```_map = {"0000" => "0", "0001" => "1", "0010" => "2", "0011" => "3", "0100" => "4", "0101" => "5", "0110" => "6", "0111" => "7", "1000" => "8",
"1001" => "9", "1010" => "A", "1011" => "B", "1100" => "C", "1101" => "D", "1110" => "E", "1111" => "F"  }
_i = 0
_output = ""

while (_input.length % 4 != 0) do
_input = "0" + _input;
end
while ( _i < _input.length)
_output = _output + _map[ _input[_i..._i + 4]]
_i = _i + 4;
end
```

### How To Convert Hexadecimal to Binary

When converting from a hexadecimal value to a binary value we have two methods for converting. The first method is we can convert each hexadecimal digit to a decimal value. We then use the converted decimal value and convert it into its corresponding binary value. The formula below is for converting a hexadecimal value into a binary value.

```Formula:
Step 1: Starting from the left toward the right of the hexadecimal string.
Step 2: Convert each hexadecimal digit to a decimal value.
Step 3: Convert each converted digit into a binary block of four binary digits.
If the hexadecimal value is zero then make it a binary block with four zero digits.
Step 4: Store the converted binary blocks into a string order from left to right.
Answer: Once every digit in the hexadecimal string is converted. The converted binary string is the value of the hexadecimal string.

Example:      Convert  AC15D0 hexadecimal to binary
Step 1:         A      C     1      5     D      0
Step 2:         10     12    1      5     13     0
Step 3:        1010   1100  0001   0101  1101   0000
Answer:        1010 1100 0001 0101 1101 0000 is the binary value of the AC15D0 hexadecimal string.
```

Looking at the above formula and turn the formula into a programming scenario, we have four procedures to make. First, we have to read the hexadecimal string from left to right one digit at a time. Second, each time we read a hexadecimal digit from the hexadecimal string with the value A to F, we have to convert that hexadecimal digit to a decimal value. Third, for every hexadecimal digit that we read, we have to convert that digit to a binary value. The binary format must be in a four digits block format. The last procedure is each time a hexadecimal number is converted to a binary value, it has to be appended to the end of the output string.

This is the variable we need to declare for comparing our hexadecimal digit from A to F to their corresponding decimal value.

```_map = {"A" => 10, "B" => 11, "C" => 12, "D" => 13, "E" => 14, "F" => 15}
```

This is the beginning of the “for” loop. We declare two variables that would hold the temporary data and the value of the variables will reset each time the loop is executed. We then assign the temp variable the current hexadecimal digit base on two conditions. If the hexadecimal value is A to F, we would look for its corresponding decimal value within our hexadecimal and decimal values’ map.

```for  _i in 0..._input.length
_temp = 0;
_tempstr = ""
_temp = _map.key?(_input[_i]) ? _map[_input[_i]] : _input[_i].to_i
```

This is the while loop that nested within our for loop to convert the current value that the temp variable is holding to a binary value. We then assign that value to our tempstr variable. The second while loop is to increase the length of the tempstr to become a four digits block of binary format if it is not already so by appending zero to the front of the string. After the two while loop, we would assign the tempstr value, which should now hold a four digits binary value, to the end of our output string.

```while ( _temp > 0) do
_tempstr = (_temp % 2 == 0) ? "0" + _tempstr : "1" + _tempstr
_temp = (_temp % 2 == 0) ? (_temp / 2) : (_temp - 1) / 2 ;
end

_tempstr = _tempstr.length == 0? "0000": _tempstr;

while( _tempstr.length % 4 != 0 ) do
_tempstr = "0" + _tempstr
end

_output += _tempstr
```

The second method for converting hexadecimal to a binary value is to create a map of binary values in a four digits block format corresponding to each hexadecimal digit from zero to F. This is my recommended solution for converting a hexadecimal value to a binary value in any programming platform. This method is my recommended method, due to this method require less execution time per digit convert. This is the formula for method two.

```Method 2:
Step 1: Make a table that maps the binary value for the hexadecimal number from zero to F. The binary format should be in a four digits block format.
Step 2: Starting from the left toward the right of the hexadecimal string, convert each hexadecimal digit to its corresponding binary value in a four digits binary block format.
Step 3: Store the order of each binary block in a string starting with the same order as reading the hexadecimal string.
Answer: When every hexadecimal digit in the hexadecimal string is converted to their corresponding binary values, the binary string is the binary value of the hexadecimal string.

Example:    Convert AABC05D0 to binary.
Step 1:       A      A       B      C      0      5      D      0
Step 2:     1010    1010    1011   1100   0000   0101   1101   0000
Answer:    1010 1010 1011 1100 0000 0101 1101 0000 is the binary value of AABC05D0
```

From the formula above, we can see that we only have three procedures to follow and that is to read through the hexadecimal string from left to right. At each time of reading, we would compare the hexadecimal value to our map variable to get the binary value of the hexadecimal digit. Then we would append the binary value to the end of our output string. The entire procedure is so short we can sum it up in seven lines of code.

```_map = {'0' => "0000", '1' => "0001", '2' => "0010", '3' => "0011",'4' => "0100", '5' => "0101", '6' => "0110", '7' => "0111",
'8' => "1000", '9' => "1001", 'A' => "1010", 'B' => "1011",'C' => "1100", 'D' => "1101", 'E' => "1110", 'F' => "1111" }
_output = ""
_input = _input.upcase
for  _i in  0..._input.length
_output = _output + _map[_input[_i]]
end
```

This is the version one of how to convert between binary numbering system and hexadecimal numbering system. Version two can be found below.

```# "Copyright Notice", please do not remove.
# Written by Kevin Ng
# The full tutorial on this subject can be found @ http://kevinhng86.iblog.website or http://programming.world.edu.
# This source code file is a part of Kevin Ng's Z library.
# This source code is licenses under CCDL-1.0  A copy of CDDL1.0 can be found at https://opensource.org/licenses/CDDL-1.0
class LibZ
def self.binhex(_input)
_map = {10 => "A", 11 => "B", 12 => "C", 13 => "D", 14 => "E", 15 => "F"}
_i = 0
_output = ""

while( _input.length % 4 != 0) do
_input = "0" + _input
end

while( _i < _input.length) do
_temp = 0
_temp = _input[_i + 3] == "0"? _temp : _temp + 1
_temp = _input[_i + 2] == "0"? _temp : _temp + 2
_temp = _input[_i + 1] == "0"? _temp : _temp + 4
_temp = _input[_i] == "0"? _temp : _temp + 8
_output = _temp > 9? _output + _map[_temp] : _output + _temp.to_s
_i = _i + 4
end

_output = _output.gsub(/^0+/, "")
_output = _output.length < 1 ? "0" : _output

return _output;
end

def self.hexbin(_input)
_map = {"A" => 10, "B" => 11, "C" => 12, "D" => 13, "E" => 14, "F" => 15}
_output = ""
_input = _input.upcase

for _i in 0... _input.length
_temp = 0;
_tempstr = ""
_temp = _map.key?(_input[_i]) ? _map[_input[_i]] : _input[_i].to_i
while (_temp > 0) do
_tempstr = (_temp % 2 == 0) ? "0" + _tempstr : "1" + _tempstr
_temp = (_temp % 2 == 0) ? (_temp / 2) : (_temp - 1) / 2 ;
end

_tempstr = _tempstr.length == 0? "0000": _tempstr;

while( _tempstr.length % 4 != 0 ) do
_tempstr = "0" + _tempstr
end

_output += _tempstr

end
return _output
end
end
# Test case below
a = "000010101000000001111111111111111111111111111111000000000000000000000000000010011111"
b = LibZ.binhex(a)
c = LibZ.hexbin(b)
puts a
puts b
puts c```

This is the version two of how to convert between binary numbering system and hexadecimal numbering system.

```# "Copyright Notice", please do not remove.
# Written by Kevin Ng
# The full tutorial on this subject can be found @ http://kevinhng86.iblog.website or http://programming.world.edu.
# This source code file is a part of Kevin Ng's Z library.
# This source code is licenses under CCDL-1.0  A copy of CDDL1.0 can be found at https://opensource.org/licenses/CDDL-1.0
class LibZ
def self.binhexZ(_input)
_map = {"0000" => "0",
"0001" => "1",
"0010" => "2",
"0011" => "3",
"0100" => "4",
"0101" => "5",
"0110" => "6",
"0111" => "7",
"1000" => "8",
"1001" => "9",
"1010" => "A",
"1011" => "B",
"1100" => "C",
"1101" => "D",
"1110" => "E",
"1111" => "F"
}
_i = 0
_output = ""

while (_input.length % 4 != 0) do
_input = "0" + _input;
end
while (_i < _input.length)
_output = _output + _map[ _input[_i..._i + 4]]
_i = _i + 4;
end

_output = _output.gsub(/^0+/, "")
_output = _output.length < 1 ? "0": _output

return _output;
end

def self.hexbinZ(_input)
_map = {'0' => "0000",
'1' => "0001",
'2' => "0010",
'3' => "0011",
'4' => "0100",
'5' => "0101",
'6' => "0110",
'7' => "0111",
'8' => "1000",
'9' => "1001",
'A' => "1010",
'B' => "1011",
'C' => "1100",
'D' => "1101",
'E' => "1110",
'F' => "1111"
}
_output = ""
_input = _input.upcase
for  _i in  0..._input.length
_output = _output + _map[_input[_i]]
end
return _output
end
end
# Test case
a = "11111111000000000001111111111100000000100001111111111111111111111111111111111111111111111111111111111111111111111100000000000000000000000000";
b = LibZ.binhexZ(a);
c = LibZ.hexbinZ(b);
puts a
puts b
puts c```

This post was written by Kevin and was first post @ http://kevinhng86.iblog.website.
Original Post Name: "Working With Number – Converting Binary And Hexadecimal – Ruby".
• 