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

Dani AI

Generated

Quick summary and practical notes for : the two answers already posted cover two common approaches. gives a fast way to read a binary string into a fixed-width container and print octal/hex with the stream manipulators (great for quick display). provides a reusable conversion routine (more general), but his implementation uses raw new and returns a char* (risk of memory leaks) and does not validate input characters—prefer std::string and explicit checks.

Recommended workflow and pitfalls to avoid

  • Normalize the input first: strip whitespace and an optional 0b/0B prefix; decide whether the input is signed or unsigned.
  • Validate that only 0 and 1 (and an optional leading -) appear. Invalid digits are the most common bug.
  • Choose a strategy:
    • Numeric route (simple): for binaries up to 64 bits, parse with std::stoull(bin, nullptr, 2) (C++11+) and format with std::oct/std::hex via an ostringstream.
    • String/grouping route (no overflow): convert by grouping bits from the right (3 bits -> octal digit, 4 bits -> hex digit). This works for arbitrarily long binary strings without big-int libraries.
    • Big-integer route: when arithmetic on huge values is needed, use a multiprecision type (Boost.Multiprecision::cpp_int).
  • Extra cautions: preserve leading zeros only if needed, and be explicit about whether a binary input should be treated as two's-complement signed data or as an unsigned bit pattern.

Example: group-based conversion (works for arbitrarily long binaries)

#include <string>
#include <algorithm>

std::string binaryToGrouped(const std::string& input, int groupBits) {
    std::string s;
    for (unsigned char c : input) if (!std::isspace(c)) s.push_back(c);
    if (s.size() >= 2 && s[0]=='0' && (s[1]=='b' || s[1]=='B')) s.erase(0,2);
    if (s.empty()) return "0";
    if (!std::all_of(s.begin(), s.end(), [](char c){ return c=='0' || c=='1'; })) return ""; // invalid
    int pad = (groupBits - (s.size() % groupBits)) % groupBits;
    s.insert(0, pad, '0');
    static const char map[] = "0123456789ABCDEF";
    std::string out;
    for (size_t i = 0; i < s.size(); i += groupBits) {
        int v = 0;
        for (int j = 0; j < groupBits; ++j) v = (v << 1) | (s[i+j]-'0');
        out.push_back(map[v]);
    }
    auto p = out.find_first_not_of('0');
    return p == std::string::npos ? "0" : out.substr(p);
}
// Use groupBits = 3 for octal, groupBits = 4 for hex.

This avoids numeric overflow, eliminates manual memory management, and complements the quick-print and template approaches already shown in the thread.

Recommended Answers

All 4 Replies

#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';
  }
}

thanksss

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;
}

thanks to you so mush & I'll try
thanks for your help

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.