Ad space (banner)
๐ŸŽObjective-C Lessons
Lesson 62 / 68

Converting between bases (binary and hexadecimal)

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

Hexadecimal is straightforward with NSLog(@"%x", value), but there is no format specifier for binary, so you implement it yourself by repeatedly dividing and taking the remainder.

In the sample code, toBinary() takes the remainder with n % 2 and builds each binary digit by inserting at the front of the string with insertString:atIndex:0. Note the idea of inserting at the front rather than appending.

A common early stumble is precisely that absence of a standard binary function. Most languages provide one, so having to write the algorithm yourself 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 Objective-C 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)