convert array numbers from binary to octal

given an array that's formed from binary numbers, create a new array by converting the binary numbers of the first to octal
i don't understand how to put everything together in the right way, could you explain please?
A number is a number. Binary and octal are different text representations of a number.

XXXXXXXXX

How many 'X' is in that string?

On decimal system, 10-based system, you would write "9".
On octal, 8-based system you would write "11" (because there are 1*8+1 X).
On binary representation, the answer is "1001".

Computer stores an integer value. The task is to read words as if they were binary/octal/decimal/hex and to show integers in binary/octal/decimal/hex format.
How are the binary numbers specified? Can you provide an example of the two arrays.
@seeplus i have to input the binary numbers, it's not specified :) i know how to convert from binary to octal but since it's a separate solution, i don't know where or how to correctly put it in my code
Something like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>
#include <bitset>
#include <vector>
#include <sstream>
#include <iomanip>

int main()
{
	const std::vector<std::string> vb = {"1010", "111", "1100", "1111"};
	std::vector<std::string> vo;

	for (const auto& n : vb) {
		std::ostringstream os;

		os << std::oct << std::bitset<32>(n).to_ulong();
		vo.push_back(os.str());
	}

	for (size_t i = 0; i < vb.size(); ++i)
		std::cout << std::setfill('0') << std::setw(8) << vb[i] << '\t' << std::setw(4) << vo[i] << '\n';
}


which displays:


00001010        0012
00000111        0007
00001100        0014
00001111        0017


Note no checking for invalid binary number.
Last edited on
thank you so much :))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
using namespace std;

string octal( string bin )
{
   if ( bin.size() % 3 ) bin = string( 3 - bin.size() % 3, '0' ) + bin;
   string result;
   for ( int i = 0; i < bin.size(); i += 3 ) result += 4 * bin[i] + 2 * bin[i+1] + bin[i+2] - 6 * '0';
   return result;
}


string binary( int n ) { return ( n < 2 ? "" : binary( n / 2 ) ) + "01"[n%2]; }


int main()
{
   for ( int i = 0; i <= 64; i++ )
   {
      cout << i << '\t' << binary( i ) << '\t' << octal( binary( i ) ) << '\n';
   }
}
thank you lots!! much appreciated:)
Topic archived. No new replies allowed.