base 2 to base 4

hello! for homework i'm writing a function that converts a decimal number to Quaternary form. i have written a function that converts decimal to binary. is there a way that i can use this program to help me with the print Quaternary function? Appreciate the help.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 
//yo yo yo! this is my print binary function bro!
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <bits.h>
using namespace std;

void printBinary(int num, ostream& os)
{
	int n = num;
	if(n==0)
		;
	else 
	{
		printBinary(static_cast<unsigned int>(n) >> 1,os);
		os<<getBit(n,0);
	}
}
Ponder this: what does the bitshift right by 1 do to a number? The base is lurking in that.


Binary can have values 0 and 1. I presume that the getBit() returns 0 or 1. There is also the modulo operator to extract least significant bits, and base 4 uses more than one bit.
Any given number, which I'll call x, exists without any radix (like binary, octal, decimal, etc). The number just is.

It is only when you want to communicate that number that you must choose a radix (or base). We humans usually pick base ten. But you could pick anything greater than one.

To decompose a number (say, x) into its digits, you must perform some divisions and remainders.

Let's say x = 25310 (that's base 10). To get '2', '5', and '3' we need to do some math:

    253 ÷ 10 = 25 R 3
    25  ÷ 10 =  2 R 5
    2   ÷ 10 =  0 R 2

Notice that the remainders were the digits of our number: 3, 5, and 2. Writing them in proper order, right-to-left, we get "2 5 3", or 253.

Let's try that again but using hexidecimal (base 16):

    253 ÷ 16 = 15 R 13
     15 ÷ 16 =  0 R 15

When we write hexadecimal numbers, we substitute the letters 'A'..'F' for the values 10..15, so "15 13" becomes "F D", or FD16. (In C++ we'd write that as 0xFD.)

This system is true of any valid radix.

Bonus thinking: why must the radix be strictly greater than 1? (What would happen if it were 1? Or zero? Or negative?)

Hope this helps.
Last edited on
we're practicing recursion. what i'm trying to do is grab 3 bits at a time using the getbit function. i know there's a getbits function but i'm not sure how to use it.
nevermind i figured it out. it was actually this.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <bits.h>
using namespace std;

void printQuaternary(int num, ostream& os)
{
	int n = num;
	if(n==0)
		;
	else 
	{
		printQuaternary(static_cast<unsigned int>(n) >> 2,os);
		os<<getBits(n,0,2);
	}
}
Topic archived. No new replies allowed.