Can anyone help me to convert from binnary to octal or hexadecimal in c++??

#include <iostream>
#include <iomanip>
#include <string>
#include <bitset>

int main()
{
  std::cout << "Enter a binary number: ";

  std::string bin;

  if (getline(std::cin, bin)) {
    std::bitset<32> bits(bin);

    std::cout << std::oct << bits.to_ulong() << '\n';
    std::cout << std::hex << bits.to_ulong() << '\n';
  }
}

Thats good if your just trying to print the values, but to actually convert between the different bases I think you have to make your own functions. I have already made them :)

#include<iostream>
using namespace std;



template<class t> inline
char *toBase(t val, int base, char *values) {
	register char d = 1;
	t c;
	register bool _signed = val < 0;
	if(val >= 0) for (c = base; c <= val; c *= base, d++);
	else for (c = -base; c>=val; c*=base, d++);
	register char i = d + _signed;
	char *bin = new char[i+1];
	if (_signed)
		bin[0]='-';
	for (val *= base; i - _signed;i--)
		bin[i-1] = values[
			(val /= base,(char) ((val % base) < 0 
			? -(val%base) : (val%base)))
		];
	bin[d + _signed]='\0';
	return bin;
}


// Returns index of first matched char
inline char GetIndex(char *str, char c) {
	for (char i = 0;str[i];i++) {
		if (str[i]==c)
			return i;
	}
	return 0;
}


template<class t> inline
t fromBase(char *val, char base, char *values) {
	t v = 0;
	for (char i=0;val[i];i++) {
		v *= base;
		v += GetIndex(values, val[i]);
	}
	return v;
}



int main() {
	/// BINARY
	char *str1 = toBase(255, 2, "01");
	cout << str1 << '\n'; // 11111111
	cout << fromBase<int>(str1, 2, "01") << "\n\n"; // Back to 255

	// OCTAL
	char *str2 = toBase(255, 8, "012345678");
	cout << str2 << '\n'; // 337
	cout << fromBase<int>(str2, 8, "012345678") << "\n\n"; // Back to 255

	// HEX
	char *str3 = toBase(255, 16, "0123456789ABCDEF");
	cout << str3 << '\n'; // FF
	cout << fromBase<int>(str3, 16, "0123456789ABCDEF") << "\n\n"; // Back to 255


	cin.ignore();
	return 0;
}
This article has been dead for over six months. Start a new discussion instead.