Integer Bases Solutions

back to the problems

p1 (base conversions)

Complete the following table by hand. For binary, write 8 digits, padding with leading zeroes if necessary. Note that the underscore is there purely for readability.

Decimal Binary Hexadecimal
1 0b0000_0001 0x1
21 0b0001_0101 0x15
129 0b1000_0001 0x81
30 0b0001_1110 0x1e

p2 (conversions in C (or not?))

Confused Cornelius posts the following question on EdStem:

I am trying to write a function that takes in an int and converts it to hex. Here's what I've gotten so far:

int convert_to_hex(int num) { // I'm stuck here...

I read over the slides and notes about doing decimal-hexadecimal conversions but I'm still confused. I can code the arithmetic, but I'm not sure what my final result should really be...?

Help Cornelius out by making a reply to his Ed question.

Hi Cornelius - I don't think what you're trying to do makes sense to do in C! I think you're assuming your function takes in a base 10, decimal integer - but decimal and hexadecimal are just written representations of an integer value. C functions just take in integer values, agnostic of any base.

The base only matters when we try to print out the integer. You can use printf to specify what base (among other options) you want the integer to be printed out as - %d for decimal and %x for hexadecimal.

p3 (base conversions using gdb)

Complete the following table with the help of gdb. Please don't use some random website that you found on Google. You know who you are.

For binary, write 8 digits, padding with leading zeroes if necessary. Note that the underscore is there purely for readability.

Decimal Binary Hexadecimal
254 0b1111_1110 0xfe
101 0b0110_0101 0x65
214 0b1101_0110 0xd6