Ad space (banner)
๐Ÿ“ŠR Lessons
Lesson 62 / 68

Converting between bases (binary and hexadecimal)

This lesson covers converting between bases in R, with the aim of deepening your understanding of how numbers are represented inside a computer.

R has no dedicated function for binary conversion, so you implement it yourself by repeatedly dividing and taking the remainder. Hexadecimal is straightforward with sprintf("%x", value).

In the sample code, to_binary() builds each binary digit by repeatedly taking the remainder with n %% 2 and the quotient with n %/% 2. Note how simply sprintf("%x", 42) handles hexadecimal by comparison.

A common early stumble is precisely that absence of a standard binary function. Most languages provide one, so having to write the algorithm yourself in R is a surprise.

Binary is used inside the computer and hexadecimal in things like colour codes — basic knowledge worth having.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run R directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)