tag:code.tutsplus.com,2005:/categories/coding-conceptsEnvato Tuts+ Code - Coding Concepts2021-04-19T14:14:10Ztag:code.tutsplus.com,2005:PostPresenter/cms-368572021-04-13T18:14:07+00:00How to Use Base64 Encoding in PHP<div content-block-type="Wysi" class="content-block-wysi">
<p>In this quick article, we’ll discuss the basics of base64 encoding in the context of PHP. Basically, we’ll see how you could use PHP functions to transform data into the base64-encoded format.</p>
<h2>What Is Base64 Encoding?</h2>
<p>Base64 is an encoding of binary data in ASCII. Each character in the string represents six bits of information. Effectively it represents the binary data in base 64 representation. Check out this <a href="https://code.tutsplus.com/articles/number-systems-an-introduction-to-binary-hexadecimal-and-more--active-10848" target="_self">primer on number systems and bases</a> if you need a refresher.</p>
<p>The primary use of Base64 encoding is to encode binary data to ASCII text, when you want to transfer such data over protocols that are specifically designed to handle textual data. This makes sure that the data remains intact while it’s transported. Specifically, Base64 is used for things like sending emails and uploading binary data in HTML forms.</p>
<p>Another common use of Base64 encoding is hashing. Of course, you’re not supposed to use Base64 encoding itself to generate hashes, since it can be easily decoded. Firstly, you generate a hash with the help of a hashing algorithm like SHA, and then you convert the resulting hash into the Base64-encoded format to display it. It’s really easy to compare two Base64-encoded checksums for integrity.</p>
<p>In the next section, we’ll discuss the built-in Base64 functions in PHP.</p>
<h2>Base64 Functions in PHP</h2>
<p>There are two main functions in PHP that deal with Base64 encoding. The <code>base64_encode</code> function allows you to encode data in the MIME Base64 format. On the other hand, the <code>base64_decode</code> function is used to decode the MIME Base64-encoded data.</p>
<p>Let’s go through each of these functions in detail.</p>
<h3>base64_encode</h3>
<p>Let’s go through the syntax of the <code>base64_encode</code> function.</p>
<pre class="brush: php noskimlinks noskimwords">base64_encode ( string $string ) : string</pre>
<p>The only argument you need to pass to the <code>base64_encode</code> function is the source string which you want to encode to MIME Base64.</p>
<p>This returns a Base64-encoded string. It’s important to note that the Base64-encoded data takes around 33% more space in memory than the original data.</p>
<h3>base64_decode</h3>
<p>Let’s go through the syntax of the <code>base64_decode</code> function.</p>
<pre class="brush: php noskimlinks noskimwords">base64_decode ( string $string , bool $strict = false ) : string|false</pre>
<p>The first argument is the Base64-encoded data which you want to decode.</p>
<p>The second argument is optional, but if you pass <code>TRUE</code>, it will perform strict checking. This means that if the Base64-encoded data contains characters from outside the Base64 alphabet, the decode function will return <code>FALSE</code>. This is useful for checking the integrity of the Base64-encoded string. On the other hand, if you want to discard invalid characters silently, just pass <code>FALSE</code>, which is the default value.</p>
<p>On successful decoding, the function returns the decoded string, otherwise it returns <code>FALSE</code>. It’s important to note that the <code>base64_decode</code> function may return binary data if the string in question was in the binary format before encoding.</p>
<p>In the next section, we’ll discuss how you can use built-in Base64 functions in PHP.</p>
<h2>How to Encode and Decode Data With MIME Base64</h2>
<p>In this section, we’ll go through a couple of examples to see Base64 functions in action.</p>
<h3>Encode URL Parameters</h3>
<p>More often than not, you’ll end up using the <code>base64_encode</code> function to encode parameters that contain URLs.</p>
<p>Let’s quickly see how it works with the following example.</p>
<pre class="brush: php noskimlinks noskimwords"><?php
$redirectUrl = 'https://www.example.com/some/other/url';
header('Location: https://www.example.com/redirect/' . base64_encode($redirectUrl));
//https://www.example.com/redirect/aHR0cDovL3d3dy5leGFtcGxlLmNvbS9zb21lL290aGVyL3VybA==
?></pre>
<p>As you can see, if we don’t use the <code>base64_encode</code> function, the resulting URL would look like <code>https://www.example.com/redirect/http://www.example.com/some/other/url</code>, which is invalid.</p>
<h3>Base64-Encoded Checksum</h3>
<p>As we discussed earlier, the <code>base64_encode</code> function comes in handy when converting binary data into an ASCII string.</p>
<p>Let’s have a look at the following example.</p>
<pre class="brush: php noskimlinks noskimwords"><?php
$base64_encoded_hash = base64_encode(hash_hmac('sha1', 'Source string to be hashed.', 'YOUR_TOP_SECRET_KEY', true));
?></pre>
<p>In the above example, the <code>hash_hmac</code> function would return hashed binary data. So if you don't use the <code>base64_encode</code> function, it would be difficult to display the resulting binary data.</p>
<h3>Email Attachments</h3>
<p>In PHP, when you send an email with file attachments, you can encode the file contents into the Base64-encoded format. In fact, if you’re sending binary attachments, then it’s essential that you encode the attachment data instead of sending it in the raw format.</p>
<p>Let’s have a look at the following example.</p>
<pre class="brush: php noskimlinks noskimwords"><?php
$to = 'receiver@example.com';
$subject = 'Example of base64 encoded attachments';
$message = 'This email contains an image attachment.';
$boundary = md5(microtime());
$headers = "From: name <from@example.com>" . "\r\n";
$headers .= "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=" . $boundary . "\r\n";
$headers .= "Multipart MIME example." . "\r\n";
$message.= "--" . $boundary. "\r\n";
$message.= "Content-Type: text/plain; charset=\"iso-8859-1\"" . "\r\n";
$message.= "Content-Transfer-Encoding: 8bit" . "\r\n";
$message.= $message . "\r\n";
// attach file
$filename = 'nature.jpg';
$filecontents = file_get_contents($filename);
$filecontents = chunk_split(base64_encode($filecontents));
$message.= "--" . $boundary. "\r\n";
$message.= "Content-Type: image/jpg; name=\"" . $filename . "\"" . "\r\n";
$message.= "Content-Transfer-Encoding: base64" . "\r\n";
$message.= "Content-Disposition: attachment" . "\r\n";
$message.= $filecontents . "\r\n";
$message.= "--" . $boundary. "--";
mail($mailto, $subject, $body, $headers);
?></pre>
<p>As you can see, we’ve used the <code>base64_encode</code> function to encode binary image data before it’s sent as an attachment.</p>
<p>In this way, you can use Base64 functions in PHP for various purposes.</p>
<h2>Conclusion</h2>
<p>In this quick article, we discussed how you can use Base64 functions in your day-to-day PHP development. </p>
</div>2021-04-19T14:14:10.000Z2021-04-19T14:14:10.000ZSajal Sonitag:code.tutsplus.com,2005:PostPresenter/active-108482014-01-20T02:02:57+00:00Number Systems: An Introduction to Binary, Hexadecimal, and More<div content-block-type="Wysi" class="content-block-wysi">
<p>Ever see crazy binary numbers and wonder what they meant? Ever see numbers with letters mixed in and wonder what's going on? You’ll find out all of this and more in this article. Hexadecimal doesn’t have to be scary.</p>
<h2>Introduction: What Is a Number System?</h2>
<p>You probably already know what a number system is—ever hear of binary numbers or hexadecimal numbers? Simply put, a number system is a way to represent numbers. We are used to using the base-10 number system, which is also called decimal. Other common number systems include base-16 (hexadecimal), base-8 (octal), and base-2 (binary).</p>
<p>In this article, I’ll explain what these different systems are, how to work with them, and why knowing about them will help you.</p>
<h2>Activity</h2>
<p>Before we get started, let’s try a little activity for fun. There are many different ways to represent a color, but one of the most common is the RGB color model. Using this model, every color is made up of a combination of different amounts of red, green, and blue.</p>
<p>You may be wondering how colors relate to number systems. In short, on a computer, any color is stored as a large number: a combination of red, green, and blue. (We’ll go into more detail on this later.) Because it’s just a number, it can be represented in multiple ways using different number systems.</p>
<p>Your job is to guess how much red, green, and blue is in the background color of the activity below. The values for red, green, and blue can range from 0 to 255.</p>
<p>Feel free to use the various hints provided to help you out. If you don’t understand the numerical hints yet, no problem! You can see what your guess looks like using the <strong>Check Guess</strong> button. And if the background color happens to make the text difficult to read, hit <strong>New Color</strong>. Right now, it may seem tricky, but hopefully by the end of the article, it will seem easy.</p>
<p><iframe src="https://codepen.io/tutsplus/embed/Qqmozz/?height=600&theme-id=12451&default-tab=result&embed-version=2" width="850" height="600" frameborder="no" scrolling="no" allowfullscreen="true" loading="lazy"></iframe></p>
<h2>Looking at Base-10</h2>
<p>0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11... You’ve counted in base-10 all of your life. Quick, what is 7+5? If you answered 12, you are thinking in base-10. Let’s take a closer look at what you’ve been doing all these years without ever thinking about it.</p>
<p>Let’s take a quick look at counting. First, you go through all the digits: 0, 1, 2... Once you hit 9, you have no more digits to represent the next number. So you change it back to 0 and add 1 to the tens digit, giving you 10. The process repeats over and over, and eventually you get to 99, where you can’t make any larger numbers with two digits, so you add another, giving you 100.</p>
<p>Although that’s all very basic, you shouldn’t overlook what's going on. The rightmost digit represents the number of ones, the next digit represents the number of tens, the next the number of hundreds, etc.</p>
<h2>Visualizing Base-10</h2>
<p>Confused by these descriptions? No problem—let’s visualize it instead. Imagine a large number, like 2347. We can represent that with two groups of one thousand, three groups of one hundred, four groups of ten, and seven individual blocks.</p>
<figure class="post_image"><img src="https://cms-assets.tutsplus.com/cdn-cgi/image/width=850/uploads/users/30/posts/9306/image/10.png" alt="Visualizing Base-10" loading="lazy" width="870px" height="420px" class="resized-image resized-image-desktop" srcset="https://cms-assets.tutsplus.com/cdn-cgi/image/width=1700/uploads/users/30/posts/9306/image/10.png 2x"><img src="https://cms-assets.tutsplus.com/cdn-cgi/image/width=630/uploads/users/30/posts/9306/image/10.png" alt="Visualizing Base-10" loading="lazy" width="650px" height="316px" class="resized-image resized-image-tablet" srcset="https://cms-assets.tutsplus.com/cdn-cgi/image/width=1260/uploads/users/30/posts/9306/image/10.png 2x"><img src="https://cms-assets.tutsplus.com/cdn-cgi/image/width=360/uploads/users/30/posts/9306/image/10.png" alt="Visualizing Base-10" loading="lazy" width="380px" height="189px" class="resized-image resized-image-mobile" srcset="https://cms-assets.tutsplus.com/cdn-cgi/image/width=720/uploads/users/30/posts/9306/image/10.png 2x">
<figcaption>Visualizing Base-10 using blocks</figcaption>
</figure>
<p>Use the tool below to output a number into its composite “groups”.</p>
<p><iframe src="https://codepen.io/tutsplus/embed/aLYxME/?height=400&theme-id=12451&default-tab=result&embed-version=2" width="850" height="400" frameborder="no" scrolling="no" allowfullscreen="true" loading="lazy"></iframe></p>
<h2>Base-10 Mathematically</h2>
<p>You may have noticed a pattern by now. Let’s look at what's going on mathematically, using 2347 as an example.</p>
<ul>
<li>As you saw, there are 2 groups of a thousand. Not coincidentally, <code>1000 = 10*10*10</code>, which can also be written as <code>10<sup>3</sup></code>.</li>
<li>There are 3 groups of a hundred. Again, not coincidentally, <code>100 = 10*10</code> or <code>10<sup>2</sup></code>.</li>
<li>There are 4 groups of ten, and, <code>10 = 10<sup>1</sup></code>.</li>
<li>Finally, there are 7 groups of one, and <code>1 = 10<sup>0</sup></code>. (That may seem strange, but <em>any</em> number to the power of 0 equals 1, by definition.)</li>
</ul>
<p>This is essentially the definition of base-10. To get a value of a number in base-10, we simply follow that pattern. Here are a few more examples:</p>
<ul>
<li><code>892 = 8*10<sup>2</sup>+9*10<sup>1</sup>+2*10<sup>0</sup></code></li>
<li><code>1147 = 1*10<sup>3</sup>+1*10<sup>2</sup>+4*10<sup>1</sup>+7*10<sup>0</sup></code></li>
<li><code>53 = 5*10<sup>1</sup>+3*10<sup>0</sup></code></li>
</ul>
<p>Admittedly, this all seems a little silly. We all know what value a base-10 number is because we always use base-10, and it comes naturally to us. As we’ll see soon, though, if we understand the patterns in the background of base-10, we can understand other bases better.</p>
<h2>Base-8</h2>
<p>On to base-8, also called octal. Base-8 means just what it sounds like: the system is based on the number eight (as opposed to ten). Remember how in base-10 we had ten digits? Now, in base-8, we are limited to only eight digits: 0, 1, 2, 3, 4, 5, 6, and 7. There’s no such thing as 8 or 9.</p>
<p>We count the same way as we normally would, except with only eight digits. Instead of a lengthy explanation, simply try out the demo below by clicking <strong>Count Up 1</strong> to see how counting in base-8 works.</p>
<p><iframe src="https://codepen.io/tutsplus/embed/xXWBOK/?height=400&theme-id=12451&default-tab=result&embed-version=2" width="850" height="400" frameborder="no" scrolling="no" allowfullscreen="true" loading="lazy"></iframe></p>
<p>You should notice a similar pattern to before; after we get to 7, we run out of different digits for any higher number. We need a way to represent eight of something. So we add another digit, change the 7 back to 0, and end up with 10. Our answer of 10 in base-8 now represents what we would normally think of as 8 in base-10.</p>
<p>Talking about numbers written in multiple bases can be confusing. For example, as we have just seen, 10 in base-8 is not the same as 10 in base-10. So, from this point on, I’ll use a standard notation where a subscript denotes the base of numbers if needed. For example, our base-8 version of 10 now looks like 10<sub>8</sub>.</p>
<p>I find it a lot easier to understand this if I change the way I read these numbers in my head, too. For example, for 10<sub>8</sub>, I read “octal one-oh” or “one-oh in base-eight”. For 10<sub><span>10</span></sub> I read “decimal one-oh” or “one-oh in base-ten”.</p>
<p>Great, so we know 10<sub>8</sub> represents eight items. (Always feel free to plug a number into the first tool for a visualization.) What’s the next number after 77<sub>8</sub>? If you said 100<sub>8</sub>, you’re correct. We know from what we’ve learned so far that the first 7 in 77<sub>8</sub> represents groups of 8, and the second 7 represents individual items. If we add these all up, we have <code>7*8 + 7*1 = 63</code>. So we have a total of 63<sub>10</sub>. So 77<sub>8</sub>=63<sub>10</sub>. We all know 64<sub>10</sub> comes after 63<sub>10</sub>.</p>
<h2>Converting From Base-8 to Base-10</h2>
<p>Let’s look at a wordier example now. John offers to give you 47<sub>8</sub> cookies, and Jane offers to give you 43<sub>10</sub> cookies. Whose offer do you take? If you want, go ahead and generate the graphic for 47<sub>8</sub> with the first tool. Let’s figure out its base-10 value so we can make the best decision!</p>
<p>As we saw when counting, the four in 47<sub>8</sub> represents the number of groups of eight. This makes sense—we are in base-8. So, in total, we have four groups of eight and seven groups of one. If we add these all up, we get <code>4*8 + 7*1 = 3910</code>. So 47<sub>8</sub> cookies is the same as 39<sub>10</sub> cookies. Jane’s offer seems like the best one now!</p>
<p>The pattern we saw before with base-10 holds true here also. We’ll look at 523<sub>8</sub>. There are five groups of 8<sup>2</sup>, two groups of 8<sup>1</sup>, and three groups of 8<sup>0</sup> (remember, 8<sup>0</sup>=1). If we add these all up, <code>5*8<sup>2</sup> + 2*8<sup>1</sup> + 3*8<sup>0</sup> = 5*64+2*8+3 = 339</code>, we get 339<sub>10</sub> which is our final answer. The diagram below shows the same thing visually:</p>
<figure class="post_image"><img src="https://cms-assets.tutsplus.com/cdn-cgi/image/width=850/uploads/users/30/posts/9306/image/base-8-to-10.png" alt="Converting 523 from base-8 to base-10" loading="lazy" width="870px" height="420px" class="resized-image resized-image-desktop" srcset="https://cms-assets.tutsplus.com/cdn-cgi/image/width=1700/uploads/users/30/posts/9306/image/base-8-to-10.png 2x"><img src="https://cms-assets.tutsplus.com/cdn-cgi/image/width=630/uploads/users/30/posts/9306/image/base-8-to-10.png" alt="Converting 523 from base-8 to base-10" loading="lazy" width="650px" height="316px" class="resized-image resized-image-tablet" srcset="https://cms-assets.tutsplus.com/cdn-cgi/image/width=1260/uploads/users/30/posts/9306/image/base-8-to-10.png 2x"><img src="https://cms-assets.tutsplus.com/cdn-cgi/image/width=360/uploads/users/30/posts/9306/image/base-8-to-10.png" alt="Converting 523 from base-8 to base-10" loading="lazy" width="380px" height="189px" class="resized-image resized-image-mobile" srcset="https://cms-assets.tutsplus.com/cdn-cgi/image/width=720/uploads/users/30/posts/9306/image/base-8-to-10.png 2x">
<figcaption>Converting 523 from base-8 to base-10</figcaption>
</figure>
<p>Here are a couple more examples:</p>
<ul>
<li><code>111<sub>8</sub> = 1*8<sup>2</sup>+1*8<sup>1</sup>+1*8<sup>0</sup> = 64+8+1 = 73<sub>10</sub></code></li>
<li><code>43<sub>8</sub> = 4*8<sup>1</sup>+3*8<sup>0</sup> = 32+3 = 35<sub>10</sub></code></li>
<li><code>6123<sub>8</sub> = 6*8<sup>3</sup>+1*8<sup>2</sup>+2*8<sup>1</sup>+3*8<sup>0</sup> = 3072+64+16+3 = 3155<sub>10</sub></code></li>
</ul>
<h2>Converting From Base-10 to Base-8</h2>
<p>Converting from base-10 to base-8 is a little trickier, but still straightforward. We basically have to reverse the process from above. Let’s start with an example: 150<sub>10</sub>.</p>
<p>We first find the largest power of 8 that is smaller than our number. Here, this is 8<sup>2</sup> or 64 (8<sup>3</sup> is 512). We count how many groups of 64 we can take from 150. This is 2, so the first digit in our base-8 number is 2. We have now accounted for 128 out of 150, so we have 22 left over.</p>
<p>The largest power of 8 that is smaller than 22 is 8<sup>1</sup> (that is, 8). How many groups of 8 can we take from 22? Two groups again, and thus our second digit is 2.</p>
<p>Finally, we are left with 6, and can obviously take 6 groups of one from this, our final digit. We end up with 226<sub>8</sub>.</p>
<p>In fact, we can make this process a touch clearer with math. Here are the steps:</p>
<ol>
<li>150/8<sup>2</sup> = 2 remainder 22</li>
<li>22/8<sup>1</sup> = 2 remainder 6</li>
<li>6/8<sup>0</sup> = 6</li>
</ol>
<p>Our final answer is then all of our non-remainder digits, or 226. Notice that we still start by dividing by the highest power of 8 that is less than our number.</p>
<h2>Dealing With Any Base</h2>
<p>It’s important to be able to apply the concepts we’ve learned about base-8 and base-10 to any base. Just as base-8 had eight digits and base-10 had ten digits, any base has the same number of digits as its base. So base-5 has five digits (0-4), base-7 has seven digits (0-6), etc.</p>
<p>Now let’s see how to find the base-10 value of any number in any base. Say we are working in base-b, where <em>b</em> can be any positive integer. We have a number d<sub>4</sub>d<sub>3</sub>d<sub>2</sub>d<sub>1</sub>d<sub>0</sub> where each d is a digit in a number. (The subscripts here don’t refer to the base of the number but simply differentiate each digit.) Our base-10 value is simply <code>d<sub>4</sub>*b<sup>4</sup> + d<sub>3</sub>*b<sup>3</sup> + d<sub>2</sub>*b<sup>2</sup> + d<sub>1</sub>*b<sup>1</sup> + d<sub>0</sub>*b<sup>0</sup></code>.</p>
<p>Here’s an example: we have the number 32311 in base-4. Notice how our number only has digits from zero to three since base-4 only has four total digits. Our base-10 value is <code>3*4<sup>4</sup> + 2*4<sup>3</sup> + 3*4<sup>2</sup> + 1*4<sup>1</sup> + 1*4<sup>0</sup> = 3*256 + 2*64 + 3*16 + 1*4 + 1*1 = 949</code>. We could, of course, follow this pattern with any amount of digits in our number.</p>
<h2>Base-16</h2>
<p>Base-16 is also called hexadecimal. It’s commonly used in computer programming, so it’s very important to understand. Let’s start with counting in hexadecimal to make sure we can apply what we’ve learned about other bases so far.</p>
<p>Since we are working with base-16, we have 16 digits. So we have 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ... and yikes! We’ve run out of digits, but we still need six more. Perhaps we could use something like a circled 10?</p>
<p>The truth is, we could, but this would be a pain to type. Instead, we simply use letters of the alphabet, starting with A and continuing to F. Here’s a table with all the digits of base-16:</p>
<table>
<thead>
<tr>
<th>Base 16 Digit</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>5</td>
</tr>
<tr>
<td>6</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>7</td>
</tr>
<tr>
<td>8</td>
<td>8</td>
</tr>
<tr>
<td>9</td>
<td>9</td>
</tr>
<tr>
<td>A</td>
<td>10</td>
</tr>
<tr>
<td>B</td>
<td>11</td>
</tr>
<tr>
<td>C</td>
<td>12</td>
</tr>
<tr>
<td>D</td>
<td>13</td>
</tr>
<tr>
<td>E</td>
<td>14</td>
</tr>
<tr>
<td>F</td>
<td>15</td>
</tr>
</tbody>
</table>
<p>Other than these extra digits, hexadecimal is just like any other base. For example, let's convert 3D<sub>16</sub> to base-10. Following our previous rules, we have: <code>3D<sub>16</sub> = 3*16<sup>1</sup> + 13*16<sup>0</sup> = 48 + 13 = 61</code>. So 3D<sub>16</sub> is equal to 61<sub>10</sub>. Notice how we use D's value of 13 in our calculation.</p>
<p>We can convert from base-10 to base-16 in a similar way to what we did with base-8. Let's convert 696<sub>10</sub> to base-16. First, we find the largest power of 16 that is less than 696<sub>10</sub>. This is 16<sup>2</sup>, or 256. Then:</p>
<ol>
<li>696/16<sup>2</sup> = 2 remainder 184</li>
<li>184/16<sup>1</sup> = 11 remainder 8</li>
<li>8/16<sup>0</sup> = 8 remainder 0</li>
</ol>
<p>We have to replace 11 with its digit representation B, and we get 2B8<sub>16</sub>.</p>
<p>Feel free to try some more conversions for practice. You can use the application below to check your answers:</p>
<p><iframe src="https://codepen.io/tutsplus/embed/JrLVrr/?height=400&theme-id=12451&default-tab=result&embed-version=2" width="850" height="400" frameborder="no" scrolling="no" allowfullscreen="true" loading="lazy"></iframe></p>
<h2>Binary! (Base-2)</h2>
<p>On to the famous base-2, also called binary. While everyone knows binary is made up of 0s and 1s, it is important to understand that it is no different mathematically than any other base. There’s an old joke that goes like this:</p>
<blockquote>“There are only 10 types of people in the world: those who understand binary and those who don’t.”</blockquote>
<p>Can you figure out what it means?</p>
<p>Let’s try a few conversions with base-2. First, we’ll convert 101100<sub>2</sub> to base-10. We have: <code>101100 = 1*2<sup>5</sup> + 1*2<sup>3</sup> + 1*2<sup>2</sup> = 32 + 8 + 4 = 4410</code>.</p>
<p>Now let’s convert 65 to binary. 2<sup>6</sup> is the highest power of 2 less than 65, so:</p>
<ol>
<li>65/2<sup>6</sup> = 1 remainder 1</li>
<li>1/2<sup>5</sup> = 0 remainder 1</li>
<li>1/2<sup>4</sup> = 0 remainder 1</li>
<li>1/2<sup>3</sup> = 0 remainder 1</li>
<li>1/2<sup>2</sup> = 0 remainder 1</li>
<li>1/2<sup>1</sup> = 0 remainder 1</li>
<li>1/2<sup>0</sup> = 1 remainder 0</li>
</ol>
<p>And thus we get our binary number, 1000001<sub>2</sub>.</p>
<p>Understanding binary is super important. I’ve included a table below to point out digits’ values.</p>
<figure class="post_image"><img src="https://cms-assets.tutsplus.com/cdn-cgi/image/width=850/uploads/users/30/posts/9306/image/table.png" alt="Powers of Two" loading="lazy" width="870px" height="170px" class="resized-image resized-image-desktop" srcset="https://cms-assets.tutsplus.com/cdn-cgi/image/width=1700/uploads/users/30/posts/9306/image/table.png 2x"><img src="https://cms-assets.tutsplus.com/cdn-cgi/image/width=630/uploads/users/30/posts/9306/image/table.png" alt="Powers of Two" loading="lazy" width="650px" height="131px" class="resized-image resized-image-tablet" srcset="https://cms-assets.tutsplus.com/cdn-cgi/image/width=1260/uploads/users/30/posts/9306/image/table.png 2x"><img src="https://cms-assets.tutsplus.com/cdn-cgi/image/width=360/uploads/users/30/posts/9306/image/table.png" alt="Powers of Two" loading="lazy" width="380px" height="84px" class="resized-image resized-image-mobile" srcset="https://cms-assets.tutsplus.com/cdn-cgi/image/width=720/uploads/users/30/posts/9306/image/table.png 2x"></figure>
<p>For example, the value of 10001<sub>2</sub> is 17, which is the sum of the values of the two 1 digits (16+1). This is nothing different than we have done before—it's just presented in an easy-to-read way.</p>
<h2>Tricks and Tips</h2>
<p>Normally, when converting between two bases that aren’t base-10, you would do something like this:</p>
<ol>
<li>Convert the number to base-10</li>
<li>Convert the result to the desired base</li>
</ol>
<p>However, there’s a trick that will let you convert between binary and hexadecimal quickly. First, take any binary number and divide its digits into groups of four. So let's say we have the number 1011101<sub>2</sub>. Divided up, we have 0101 1101. Notice how we can just add extra zeroes to the front of the first group to make even groups of 4. We now find the value for each group as if it were its own separate number, which gives us 5 and 13. Finally, we simply use the corresponding hexadecimal digits to write out the base-16 number, 5D<sub>16</sub>.</p>
<p>We can also go in the other direction, by converting each hexadecimal digit into four binary digits. Try converting B7<sub>16</sub> to binary. You should get 10110111<sub>2</sub>.</p>
<p>This trick works because 16 is a power of 2. What this means is that we use a similar trick for base-8, which is also a power of 2:</p>
<figure class="post_image"><img src="https://cms-assets.tutsplus.com/cdn-cgi/image/width=850/uploads/users/30/posts/9306/image/table-2.png" alt="Base-8 to Binary" loading="lazy" width="870px" height="320px" class="resized-image resized-image-desktop" srcset="https://cms-assets.tutsplus.com/cdn-cgi/image/width=1700/uploads/users/30/posts/9306/image/table-2.png 2x"><img src="https://cms-assets.tutsplus.com/cdn-cgi/image/width=630/uploads/users/30/posts/9306/image/table-2.png" alt="Base-8 to Binary" loading="lazy" width="650px" height="242px" class="resized-image resized-image-tablet" srcset="https://cms-assets.tutsplus.com/cdn-cgi/image/width=1260/uploads/users/30/posts/9306/image/table-2.png 2x"><img src="https://cms-assets.tutsplus.com/cdn-cgi/image/width=360/uploads/users/30/posts/9306/image/table-2.png" alt="Base-8 to Binary" loading="lazy" width="380px" height="147px" class="resized-image resized-image-mobile" srcset="https://cms-assets.tutsplus.com/cdn-cgi/image/width=720/uploads/users/30/posts/9306/image/table-2.png 2x"></figure>
<p>Of course, you can also reverse the process to go from base-8 to binary.</p>
<p>Here are a few other examples:</p>
<h3>Converting Binary to Hexadecimal</h3>
<p>Let's try to convert 100111100110<sub>2</sub> to hexadecimal. When we break it into units of 4, we get 1001, 1110, and 0110. Their values in decimal are 9, 14, and 6 respectively. Converting them to hexadecimal will give us 9, E, and 6. So our number will be 9E6 in hexadecimal.</p>
<h3>Converting Hexadecimal to Binary</h3>
<p>Now we will change the hexadecimal number A1D<sub>16</sub> to binary. We begin by converting each separate digit to its decimal counterpart. A, 1, and D therefore become 10, 1, and 13 respectively. Now we just convert these decimals into binary to get 1010, 0001, and 1101 respectively. The final binary representation becomes 101000011101<sub>2</sub>.</p>
<h3>Converting Binary to Octal</h3>
<p>We can use a similar technique to convert binary to octal. This time, we will divide our numbers into groups of 3 because 2^3 = 8. Let's say you want to convert 1111101<sub>2</sub> to its octal value. Dividing it into units of 3 starting from the rightmost end will give us 1, 111, and 101. Now, we can just calculate the value of these segments to get the octal representation. None of the units will have a value above 7, so we can just combine them directly to get the octal value. The values 1, 111, and 101 will become 1, 7, and 5 in octal respectively. So our number in octal representation will be 175<sub>8</sub>.</p>
<h3>Converting Octal to Binary</h3>
<p>Finally, we will convert the octal number 7245<sub>8</sub> to binary. Separating the number into individual digits will give us 7, 2, 4, and 5. We can now convert them to binary such that each representation has 3 digits. This means that 7, 2, 4, and 5 will become 111, 010, 100, and 101 respectively. Combining them all will give us 111010100101 as the correct binary representation.</p>
<h2>Conclusion</h2>
<p>Let’s go all the way back and revisit the color guessing game.</p>
<p><iframe src="https://codepen.io/tutsplus/embed/Qqmozz/?height=600&theme-id=12451&default-tab=result&embed-version=2" width="850" height="600" frameborder="no" scrolling="no" allowfullscreen="true" loading="lazy"></iframe></p>
<p>When converted to hexadecimal, the first two digits represent the amount of red, the next two the amount of green, and the final two the amount of blue. So, if our color is 17FF18<sub>16</sub>, we can easily tell that our red component is 17<sub>16</sub>, or 23<sub>10</sub>. Our green component is FF<sub>16</sub>, or 255<sub>10</sub>. Finally, our blue component is 18<sub>16</sub>, or 24<sub>10</sub>. If we are given the base-10 version of our color, 1572632<sub>10</sub>, we need to convert it to hexadecimal before we can tell anything about it.</p>
<p>Try the game again, and see how much better you can do!</p>
<p>Understanding different number systems is extremely useful in many computer-related fields. Binary and hexadecimal are very common, and I encourage you to become very familiar with them. Thanks for reading—I hope you’ve learned a lot from this article! If you have any questions, please ask them below.</p>
<p><em>This post has been updated with contributions from <a href="https://tutsplus.com/authors/monty-shokeen" target="_self">Monty Shokeen</a>. Monty is a full-stack developer who also loves to write tutorials and to learn about new JavaScript libraries. </em></p>
</div>2021-03-31T14:50:08.000Z2021-03-31T14:50:08.000ZJason Killian