Convert a number from base 2 to base 6
Last Updated :
23 Jul, 2025
Given a binary integer N, the task is to convert it into base 6.
Note: The number of bits in N is up to 100.
Examples:
Input: N = "100111"
Output: 103
Explanation: The given integer (100111)2 is equivalent to (103)6.
Input: N = "1111111"
Output: 331
Approach: The given problem can be solved by first converting the given integer to decimal, thereafter converting the number from decimal to the base 6 using an approach discussed here. Please note that since the value of the N can reach up to 2100, the 128-bit integer can be used to store the decimal number.
Below is the implementation of the above approach:
C++
// C++ program of the above approach
#include <bits/stdc++.h>
using namespace std;
// Program to convert the base of
// given binary number to base 6
void convertBase(string N)
{
// 128 bit integer to store
// the decimal conversion
__int128 decimal = 0;
// Loop to iterate N
for (int i = 0; i < N.length(); i++) {
// Binary to decimal
decimal = decimal * 2 + (N[i] - '0');
}
// Stores the base 6 int
vector<int> ans;
// Decimal to base 6
while (decimal > 0) {
ans.push_back(decimal % 6);
decimal = decimal / 6;
}
// Print Answer
for (int i = ans.size() - 1; i >= 0; i--) {
cout << ans[i];
}
}
// Driver Code
int main()
{
string N = "100111";
convertBase(N);
return 0;
}
C
// C program to implement the above approach
#include <stdio.h>
#include <stdint.h>
#include <string.h>
// Program to convert the base of
// given binary number to base 6
void convertBase(char* N)
{
// 128 bit integer to store
// the decimal conversion
__int128 decimal = 0;
//calculating length of N
int len = strlen(N);
// Loop to iterate N
for (int i = 0; i < len; i++) {
// Binary to decimal
decimal = decimal * 2 + (N[i] - '0');
}
// Stores the base 6 int
int ans[len];
//to calculate index in ans
int pos = 0;
// Decimal to base 6
while (decimal > 0) {
ans[pos++] = (decimal % 6);
decimal = decimal / 6;
}
// Print Answer
for (int i = pos - 1; i >= 0; i--) {
printf("%d", ans[i]);
}
}
// Driver Code
int main()
{
char* N = "100111";
convertBase(N);
return 0;
}
// This code is contributed by phalasi.
Java
// JAVA program of the above approach
import java.util.*;
class GFG {
// Program to convert the base of
// given binary number to base 6
public static void convertBase(String N)
{
// 128 bit integer to store
// the decimal conversion
int decimal = 0;
// Loop to iterate N
for (int i = 0; i < N.length(); i++) {
// Binary to decimal
decimal = decimal * 2 + (N.charAt(i) - '0');
}
// Stores the base 6 int
ArrayList<Integer> ans = new ArrayList<Integer>();
// Decimal to base 6
while (decimal > 0) {
ans.add(decimal % 6);
decimal = decimal / 6;
}
// Print Answer
for (int i = ans.size() - 1; i >= 0; i--) {
System.out.print(ans.get(i));
}
}
// Driver Code
public static void main(String[] args)
{
String N = "100111";
convertBase(N);
}
}
// This code is contributed by Taranpreet
Python3
# Python code for the above approach
# Program to convert the base of
# given binary number to base 6
def convertBase(N):
# 128 bit integer to store
# the decimal conversion
decimal = 0
# Loop to iterate N
for i in range(len(N)):
# Binary to decimal
decimal = decimal * 2 + (ord(N[i]) - ord('0'))
# Stores the base 6 int
ans = []
# Decimal to base 6
while (decimal > 0):
ans.append(decimal % 6)
decimal = decimal // 6
# Print Answer
for i in range(len(ans) - 1, -1, -1):
print(ans[i], end="")
# Driver Code
N = "100111"
convertBase(N)
# This code is contributed by gfgking
C#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
class GFG {
// Program to convert the base of
// given binary number to base 6
public static void convertBase(string N)
{
// 128 bit integer to store
// the decimal conversion
int decimall = 0;
// Loop to iterate N
for (int i = 0; i < N.Length; i++) {
// Binary to decimal
decimall = decimall * 2 + (N[i] - '0');
}
// Stores the base 6 int
List<int> ans = new List<int>();
// Decimal to base 6
while (decimall > 0) {
ans.Add(decimall % 6);
decimall = decimall / 6;
}
// Print Answer
for (int i = ans.Count - 1; i >= 0; i--) {
Console.Write(ans[i]);
}
}
// Driver Code
public static void Main()
{
string N = "100111";
convertBase(N);
}
}
// This code is contributed by sanjoy_62.
JavaScript
<script>
// JavaScript code for the above approach
// Program to convert the base of
// given binary number to base 6
function convertBase(N)
{
// 128 bit integer to store
// the decimal conversion
let decimal = 0;
// Loop to iterate N
for (let i = 0; i < N.length; i++)
{
// Binary to decimal
decimal = decimal * 2 +
(N[i].charCodeAt(0) -
'0'.charCodeAt(0));
}
// Stores the base 6 int
let ans = [];
// Decimal to base 6
while (decimal > 0) {
ans.push(decimal % 6);
decimal = Math.floor(decimal / 6);
}
// Print Answer
for (let i = ans.length - 1; i >= 0; i--) {
document.write(ans[i]);
}
}
// Driver Code
let N = "100111";
convertBase(N);
// This code is contributed by Potta Lokesh
</script>
Time Complexity: O(len(N))
Auxiliary Space: O(1)
Another Approach: The given problem can also be solved by maintaining the integer in base 6 in place of the decimal conversion while converting the base of the binary integer to decimal. It is known that the binary number can be converted to a decimal using the following steps:
N = "1001"
N can be converted to (N)10 with the equation: (((1*2 + 0) *2 + 0) *2) + 1).
Hence, two types of steps are required, multiplying the integer by 2 which is equivalent to adding the integer in itself, and adding 0 or 1 to the integer as (0, 1)2 is equivalent to (0, 1)6. Hence, maintain a string representing a base 6 integer, and in each step, add the integer to itself and add 0 or 1 accordingly in each step. If can be done using the approach discussed here.
Below is the implementation of the above approach:
C++
// C++ program of the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find the sum of
// two integers of base B
string sumBaseB(string a, string b, int base)
{
int len_a, len_b;
len_a = a.size();
len_b = b.size();
string sum, s;
s = "";
sum = "";
int diff;
diff = abs(len_a - len_b);
// Padding 0 in front of the
// number to make both numbers equal
for (int i = 1; i <= diff; i++)
s += "0";
// Condition to check if the strings
// have lengths mis-match
if (len_a < len_b)
a = s + a;
else
b = s + b;
int curr, carry = 0;
// Loop to find the find the sum
// of two integers of base B
for (int i = max(len_a, len_b) - 1; i > -1; i--) {
// Current Place value for
// the resultant sum
curr = carry + (a[i] - '0') + (b[i] - '0');
// Update carry
carry = curr / base;
// Find current digit
curr = curr % base;
// Update sum result
sum = (char)(curr + '0') + sum;
}
if (carry > 0)
sum = (char)(carry + '0') + sum;
return sum;
}
// Program to convert the base of
// given binary number to base 6
string convertBase(string N)
{
// Stores the required answer
string ans = "0";
// Loop to iterate N
for (int i = 0; i < N.length(); i++) {
// Multiply the current
// integer with 2
ans = sumBaseB(ans, ans, 6);
// Add N[i] to ans
ans = sumBaseB(ans, (N[i] == '0')
? "0"
: "1",
6);
}
// Return Answer
return ans;
}
// Driver Code
int main()
{
string N = "100111";
cout << convertBase(N);
return 0;
}
Java
// Java program of the above approach
class GFG{
// Function to find the sum of
// two integers of base B
static String sumBaseB(String a, String b, int base)
{
int len_a, len_b;
len_a = a.length();
len_b = b.length();
String sum, s;
s = "";
sum = "";
int diff;
diff = Math.abs(len_a - len_b);
// Padding 0 in front of the
// number to make both numbers equal
for (int i = 1; i <= diff; i++)
s += "0";
// Condition to check if the Strings
// have lengths mis-match
if (len_a < len_b)
a = s + a;
else
b = s + b;
int curr, carry = 0;
// Loop to find the find the sum
// of two integers of base B
for (int i = Math.max(len_a, len_b) - 1; i > -1; i--) {
// Current Place value for
// the resultant sum
curr = carry + (a.charAt(i) - '0') + (b.charAt(i) - '0');
// Update carry
carry = curr / base;
// Find current digit
curr = curr % base;
// Update sum result
sum = (char)(curr + '0') + sum;
}
if (carry > 0)
sum = (char)(carry + '0') + sum;
return sum;
}
// Program to convert the base of
// given binary number to base 6
static String convertBase(String N)
{
// Stores the required answer
String ans = "0";
// Loop to iterate N
for (int i = 0; i < N.length(); i++) {
// Multiply the current
// integer with 2
ans = sumBaseB(ans, ans, 6);
// Add N[i] to ans
ans = sumBaseB(ans, (N.charAt(i) == '0')
? "0"
: "1",
6);
}
// Return Answer
return ans;
}
// Driver Code
public static void main(String[] args)
{
String N = "100111";
System.out.print(convertBase(N));
}
}
// This code contributed by shikhasingrajput
Python3
# Python program of the above approach
# Function to find the sum of
# two integers of base B
def sumBaseB(a, b, base):
len_a = len(a);
len_b = len(b);
s = ""
sums = ""
diff = abs(len_a - len_b)
# Padding 0 in front of the
# number to make both numbers equal
for i in range(1, diff + 1):
s += "0"
# Condition to check if the strings
# have lengths mis-match
if (len_a < len_b):
a = s + a
else:
b = s + b
curr, carry = 0, 0
# Loop to find the find the sum
# of two integers of base B
i = max(len_a, len_b) - 1
while (i > -1):
curr = carry + int(a[i]) + int(b[i])
carry = int(curr / base)
curr = curr % base
sums = str(curr) + sums
i -= 1
if carry > 0:
sums = str(carry) + sums
return sums
# function to convert base of binary num to base 6
def convertBase(N):
ans = ""
for i in range(0, len(N)):
ans = sumBaseB(ans, ans, 6)
ans = sumBaseB(ans, ["1", "0"][N[i] == "0"], 6)
return ans
N = "100111"
print(convertBase(N))
# This code is contributed by phalasi.
C#
// C# program of the above approach
using System;
class GFG{
// Function to find the sum of
// two integers of base B
static string sumBaseB(string a, string b, int base1)
{
int len_a, len_b;
len_a = a.Length;
len_b = b.Length;
string sum, s;
s = "";
sum = "";
int diff;
diff = Math.Abs(len_a - len_b);
// Padding 0 in front of the
// number to make both numbers equal
for (int i = 1; i <= diff; i++)
s += "0";
// Condition to check if the Strings
// have lengths mis-match
if (len_a < len_b)
a = s + a;
else
b = s + b;
int curr, carry = 0;
// Loop to find the find the sum
// of two integers of base B
for (int i = Math.Max(len_a, len_b) - 1; i > -1; i--) {
// Current Place value for
// the resultant sum
curr = carry + (a[i] - '0') + (b[i] - '0');
// Update carry
carry = curr / base1;
// Find current digit
curr = curr % base1;
// Update sum result
sum = (char)(curr + '0') + sum;
}
if (carry > 0)
sum = (char)(carry + '0') + sum;
return sum;
}
// Program to convert the base of
// given binary number to base 6
static string convertBase(string N)
{
// Stores the required answer
string ans = "0";
// Loop to iterate N
for (int i = 0; i < N.Length; i++) {
// Multiply the current
// integer with 2
ans = sumBaseB(ans, ans, 6);
// Add N[i] to ans
ans = sumBaseB(ans, (N[i] == '0')
? "0"
: "1",
6);
}
// Return Answer
return ans;
}
// Driver Code
public static void Main(string[] args)
{
string N = "100111";
Console.WriteLine(convertBase(N));
}
}
// This code is contributed by ukasp.
JavaScript
// JS program of the above approach
// Function to find the sum of
// 2 integers of base B
function sumBaseB(a, b, base)
{
var len_a = a.length;
var len_b = b.length;
var s = "";
var sums = "";
var diff = Math.abs(len_a - len_b);
// Padding 0 in front of the number to
// make the both numbers equal
for (var i = 1; i <= diff; i++)
{
s += "0";
}
// condition to check if the strings
// have mismatch in lengths
if (len_a < len_b)
{
a = s + a;
}
else
{
b = s + b;
}
var curr = 0;
var carry = 0;
// loop to find the sum of 2
// integers of base B
var i = Math.max(len_a, len_b) - 1
while (i > -1)
{
curr = carry + parseInt(a[i]) + parseInt(b[i]);
carry = parseInt(curr / base);
curr %= base;
sums = String(curr) + sums;
i--;
}
if (carry > 0)
sums = String(carry) + sums;
return sums;
}
// function to convert base 2 number to base 6
function convertBase(N)
{
let ans = "";
for (var i = 0; i < N.length; i++)
{
ans = sumBaseB(ans, ans, 6);
ans = sumBaseB(ans, (N[i] == "0") ? "0" : "1", 6);
}
return ans;
}
// Driver code
let N = "100111";
document.write(convertBase(N));
//This code is contributed by phasing17.
Time Complexity: O(len(N)2)
Auxiliary Space: O(len(N))
Note that the complexity of 1st approach is less than the second approach but the first approach can only handle binary integers up to 127 bits while the second approach can handle much larger values as well.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem