How To Convert Binary To Octal In C

In the computer, we can express numbers using a number system, which is a method or a system of writing. It is a type of mathematical notation used to logically express numbers from a specified set using digits or other symbols.

We can uniquely represent each number thanks to the number system. It displays the figures’s algebraic and mathematical structure. Not only that but it also lets us perform arithmetic operations like addition, subtraction, and division. The value of a digit in a number is usually determined by:

  • The digit
  • The position of it in the number
  • The base of the number system

Octal number employs numbers ranging from 0 to 7 and has an eight-base. In addition to Binary, Decimal, and Hexadecimal number systems, there are more categories of number systems. The numerals with an 8-bit base are denoted by the octal sign. The use and significance of octal numbers are numerous. It is frequently used in computer fundamentals.

By first converting a binary number to a decimal number and a decimal number to an octal number, we can convert octal numbers to decimal numbers and binary numbers to octal numbers.

The steps listed below can be used to convert binary numbers to octal numbers:

  • Consider the binary number.
  • Each digit should be multiplied by 2n-1, where n is the digit’s distance from the decimal.
  • The outcome is the binary number’s corresponding decimal number.
  • The decimal number by eight.
  • Take note of the rest
  • Until the quotient is zero, repeat the previous two steps with the quotient.
  • Reverse the order of the remainders.

The outcome is the necessary binary number in octal format.

Binary NumberOctal Number
00
11
102
113
1004
1015
1106
1117

Example : Convert binary number 0110 011.1011 into octal number. Since there is binary point

here and fractional part. So,

binary to octal fractional part

Therefore, Binary to octal is.

= (0110 011.1011)2

= (0 110 011 . 101 1)2

= (110 011 . 101 100)2

= (6 3 . 5 4)8

= (63.54)8

Why Is There A Need To Convert Binary to Octal In C

The Octal Number refers to a system of numbers with an eight-digit base with digits ranging from 0 to 7. The term ‘octal’ is used to describe numbers with an eight base. The octal numbers are important and have various uses, including in digital numbering systems and computers.

By first converting a binary number to a decimal number and then a decimal number to an octal number, octal numbers can be translated to binary numbers and binary numbers to octal numbers in the number system. Base 2 is used to represent the binary number system, base 10 is used to represent the decimal number system, and base 16 is used to represent the hexadecimal number system, all of which are similar to the octal number system.

We are required to convert the binary to octal number for the following reasons.   

  • Less  Computation and Error – Compared to the decimal and hexadecimal number systems, octal numbers employ fewer digits. There are consequently fewer computations and fewer computational errors. Any binary digit may be represented using only 3 bits, and binary to octal conversions are straightforward.
  • Aviation Code: In aviation, the transponders of the aircraft send a code in order to recognise one another. The octal number system, which has a base of 8, is used in this code.
  • UNIX/LINUX Operating System:  In UNIX/LINUX Operating System , modify a file’s permissions by using the chmod command. To modify the permissions of a file or directory, you must be the owner of the object or the superuser.  The chmod command has two modes for setting permissions:

Absolute Mode – Use integers to indicate file permissions in absolute mode (the method most commonly used to set permissions). Each triplet’s permissions should be represented by an octal mode number when changing permissions using the absolute mode.

Symbolic Mode – Employ letter and symbol combinations to add or remove permissions in the symbolic mode.

Octal ValueFile Permissions SetPermissions Description
0No permissions
1–xExecute permission only
2-w-Write permission only
3-wxWrite and execute permissions
4r–Read permission only
5r-xRead and execute permissions

Approaches to Convert Binary to Octal

Numerous approaches may be used to convert the Binary number system to the Octal number system. There are three  ways to convert the Binary number system to Octal number system in C.

  • Approach-1: Using Function
  • Approach-2: Using While Loop (Direct Method)
  • Approach-3: Using Address Assignment

Lets dive in details for each approach.

Approach-1: Using Function

In C, a Binary  may be converted into an octal number  using a for loop. To demonstrates this approach, an algorithm and c  program is created which shown below:

Algorithm:

Step-1: User to provide a binary number, which will be saved in a lengthy binary.

Step-2: Using the ideas we covered previously, the function convertBinarytoOctal(binary) is called, and a while loop is used to do calculations on the input.

Step-3: The output is printed on the console with the result.

To demonstrates this approach, a program is created which code is given below:

Code:

// C program to demonstrates conversion of binary to octal using function
#include <math.h>
#include <stdio.h>
//Convert Binary number to decimal
int binaryToDecimal(long num) {
  int decimal = 0, i = 0, rem;
  while (num != 0) {
    rem = num % 10;
    num /= 10;
    decimal += rem * pow(2, i++);
  }
  return decimal;
}
//Convert Decimal number to Octal
int convertBinarytoOctal(long binary) {
  int octal = 0, decimal = 0, i = 0;
  while (binary != 0) {
  int temp = binary % 1000;
    octal += binaryToDecimal(temp) * pow(10, i++);
    binary = binary / 1000;
  }
  return octal;
}
int main() {
  long binary;
  printf("Enter a binary number: ");
  scanf("%ld", &binary);
  printf("%ld in binary is %d in octal", binary, convertBinarytoOctal(binary));
  return 0;
}

Output:

Enter a binary number: 101011
The equivalent octal value of binary number 1010101 is: 53

Code Explanation:

  • Receive any binary number from the user.
  • Using Function  Convert Binary number to decimal number system .
  • Using Function  convert Decimal number system to octal number system.

Approach-2: Using While Loop (Direct Method)

An alternative approach of converting Binary to Octal Number System is to use While loop. To demonstrates this approach, an algorithm and c  program is created which shown below:

Algorithm:

Step-1: User enters binary number that  stores in binary variable.

Step-2: Initialize a resulting octal variable by 0.

Step-3: Compute the last three digits of binary say digits.

Step-4: Compute the octal equivalent of the three binary digits found above.

Step-5: Add octal value of binary found in above step to octal, by increasing the place value.

Step-6: Remove the last three digits of the binary number. Since they are processed, say binary = binary / 1000.

Step-7: Increase the place value of octal by using place = place * 10.

Step-8: Repeat step 3 to 7 till binary > 0.

Code:

// C program to demonstrates conversion of binary to octal using while loop
#include <stdio.h>
int main()
{
    int octConst[] = {0, 1, 10, 11, 100, 101, 110, 111};
    long long binary, oct, temp;
    int digit, place, i;
    oct = 0;
    place= 1;
    printf("Enter any binary number: ");     // User enter a Input binary number 
    scanf("%lld", &binary);
    temp = binary;          // Assign actual binary number to temp variable 
    while(temp != 0)
    {
        digit = temp % 1000;
        
        for(i=0; i<8; i++)       // Find octal equivalent of 3 digit binary 
        {
            if(octConst[i] == digit) 
            {
             
              oct = (i * place) + oct; // Increase the value of octal and add the previous octal value
                break;
            }
        }
        /* Remove the last three digit of binary */
        temp /= 1000;
        /* Increase the place value */
        place *= 10; 
    }
    printf("Actual binary number = %lld\n", binary);
    printf("Equivalent Octal number = %lld", oct);
    return 0;
}

Output:

Enter any binary number: 11101111
Actual binary number = 11101111
Equivalent Octal number = 357

Code Explanation:

  • This C code converts a binary number to an octal number.
  •  It takes a binary number as input from the user, extracts the digits in groups of three, finds their octal equivalent using a predefined array.
  • Combine them to get the final octal number.

Approach-3: Using Address Assignment

The C programming language’s powerful pointers feature has various benefits. The following are some benefits of pointers in C:

Dynamic memory allocation: Pointers allow programmers to allocate memory dynamically during runtime, which can be useful when dealing with unknown or changing data sizes.

Passing arguments to functions: Pointers are often used to pass arguments to functions, which can be more efficient than passing data by value. This is because passing data by value requires creating a copy of the data, which can be time-consuming and use a lot of memory.

Pointers to functions: In C, it is possible to create pointers to functions. This allows for the creation of more flexible and reusable code, as functions can be passed as arguments to other functions.

Algorithm: 

Step-1: Ask the user to enter a binary number

Step-2:  Read the binary number entered by the user and store it in binaryNumber

Step-3: Set octalNumber to 0

Step-4: Create a function called binaryToOctal which takes binaryNumber and octalNumber as arguments.  In binaryToOctal function:

       a. Set decimalNumber to 0 and i to 0

       b. Use a while loop to convert the binary number to decimal number:

         i. Check if binaryNumber is not equal to 0

         ii. Calculate decimalNumber as decimalNumber += (binaryNumber % 10) * pow(2, i)

         iii. Increment i by 1

         iv. Divide binaryNumber by 10

   c. Set i to 1

        d. Use a while loop to convert the decimal number to octal number:

              i. Check if decimalNumber is not equal to 0

             ii. Calculate octalNumber as octalNumber += (decimalNumber % 8) * i

             iii. Divide decimalNumber by 8

             iv. Multiply i by 10

Step-5: Call the binaryToOctal function with binaryNumber and octalNumber as arguments

Step-6: Print the octal equivalent of the binary number

Code:

// C code to convert binary number to octal number using Address Assignment
 #include <stdio.h>
#include <math.h>
void binaryToOctal(long long binaryNumber, int *octalNumber);
int main() {
    long long binaryNumber;
    int octalNumber = 0;
    printf("Enter a binary number: ");
    scanf("%lld", &binaryNumber);
    binaryToOctal(binaryNumber, &octalNumber);
    printf("Equivalent Octal number : %d", octalNumber);
    return 0;
}
void binaryToOctal(long long binaryNumber, int *octalNumber) {
    int decimalNumber = 0, i = 0;
    while(binaryNumber != 0) {
        decimalNumber += (binaryNumber % 10) * pow(2, i);
        ++i;
        binaryNumber /= 10;
    }
    i = 1;
    while(decimalNumber != 0) {
        *octalNumber += (decimalNumber % 8) * i;
        decimalNumber /= 8;
        i *= 10;
    }
}

Output:

Enter a binary number: 110111
Equivalent Octal number is : 67

Code Explanation:

  • Preprocessor directives that include two header files, stdio.h and math.h.
  • We create a variable called binaryNumber for user input and octal number for user output.
  • Next we create a function called binaryToOctal() that takes two parameters. The first one is our input number (binaryNumber) and the second one is a pointer that points to our output variable location in the memory.
  •  As our execution starts with main function so we call binaryToOctal() function in our main, the working of binaryToOctal() is as follows:
  • In binaryToOctal() we initialize two variables i.e. decimal number and i and first we convert our binary number into decimal using while loop, so until our binary number becomes 0 we just we get the remainder of binary number and then multiply with pow(2,i) which will give us decimal number.
  • Next we convert decimal numbers into octal using our approach remainder, multiply and divide.
  • The main importance of using pointers here is only one memory location we need to update.

Best Approach- Address Assignment Approach

The best approach to convert binary to octal number is the address assignment approach using a pointer where user input entered in binary and  print equivalent octal number. It is the best approach because:

  • Programmer Convenient: It is a short and very convenient way to convert binary to octal numbers.
  • Reduce Code Length: It offers reducing length of code by replacing numbers of lines.
  • Efficient: This approach is considered as efficient in time complexity.

Sample problems related to convert binary to octal

Sample Problem-1: Using Approach-1

Problem Definition: Consider an aviation company processes aviation code in decimal representation that generates in binary representation. Therefore, create an algorithm and  C  program to demonstrate binary to octal conversions.

Solution: An algorithm for this problem is represented in the following steps.

Algorithm:

Step-1: First take Aviation code which is represented in binary form 

Step-2: Then, convert binary aviation code into decimal form using while loop 

Step-3: Convert decimal to octal form using while loop

Step-4: Return octal value of aviation code which is equivalent to binary aviation code .

To demonstrates this approach, a program is created which code is given below:

Code:

// C program to demonstrates conversion of binary to octal using approach-1
#include <math.h>
#include <stdio.h>
//Convert Aviationcode number to decimal
int binaryToDecimal(long num) {
  int decimal = 0, i = 0, rem;
  while (num != 0) {
    rem = num % 10;
    num /= 10;
    decimal += rem * pow(2, i++);
  }
  return decimal;
}
//Convert Decimal number to Octal
int convertBinarytoOctal(long Aviationcode) {
  int octal = 0, decimal = 0, i = 0;
  while (Aviationcode != 0) {
    int temp = Aviationcode % 1000;
    octal += binaryToDecimal(temp) * pow(10, i++);
    Aviationcode = Aviationcode / 1000;
  }
  return octal;
}
int main() Enter a Aviation code in binary : 111
111 in Aviation Code is 7 in octal

  long Aviationcode;
  printf("Enter a Aviation code in binary : ");
  scanf("%ld", &Aviationcode);
  printf("%ld in Aviationcode is %d in octal", Aviationcode, convertBinarytoOctal(Aviationcode));
  return 0;
}

Output:

Enter a Aviation code in binary : 111
111 in Aviation Code is 7 in octal

Code Explanation:

  • Receive Activationcode in  binary number from the user.
  • Using Function  Convert Binary number to decimal number system  .
  • Using Function  convert Decimal number system to octal number system.

Sample Problem-2: Using Approach-2

Problem Definition:  In many digital systems, an activation code is represented in the binary form. But to process and reduce the length of the code  of the activation codes we require converting binary to octal representation. Therefore, create an algorithm and  C  program to demonstrate binary to octal conversions.

Solution: An algorithm for this approach is represented in the following steps.

Algorithm: 

Step-1: Input activation binary number from user. Store it in a variable, say activationcode.

Step-2: Initialize a variable to store converted octal say octal = 0.

Step-3: Find the last three digits of binary say digit = num % 1000.

Step-4: Find the octal equivalent (using binary to octal table) of the three binary digits found above.

Step-5: Then return the octal value of activation code which is presented in binary .

Code:

// C program to demonstrates conversion of binary to octal using approach-2
#include <stdio.h>
int main()
{
    int octalConstant[] = {0, 1, 10, 11, 100, 101, 110, 111};
    long long activationcode, octal, tempBinary;
    int digit, place, i;
    octal = 0;
    place= 1;
    
    /* Input binary number from user */
    printf("Enter any activation code number: ");
    scanf("%lld", &activationcode);
    /* Copy original binary value to temp variable */
    tempBinary = activationcode;
    while(tempBinary != 0)
    {
        /* Extract last three digit of binary */
        digit = tempBinary % 1000;
        /* Find octal equivalent of 3 digit binary */
        for(i=0; i<8; i++)
        {
            if(octalConstant[i] == digit)
            {
                /*
                 * Increase the value of octal
                 * and add the previous octal value
                 */
                octal = (i * place) + octal;
                break;
            }
        }
        /* Remove the last three digit of binary */
        tempBinary /= 1000;
        /* Increase the place value */
        place *= 10; 
    }
    printf("Original activation code = %lld\n", activationcode);
    printf("Equivalent Activation octal number = %lld", octal);
    return 0;
}

Output:

Enter any activation code number: 111
Original activation code = 111
Equivalent Activation octal number = 7

Code Explanation:

  • First taking binary activation code from the user.
  • Second, find the equivalent octal code using a while loop.

Sample Problem-3:Using Approach-3

Problem Definition: Consider a computer program executing file permissions instruction in binary form . To process results in octal form, then it is required to convert to octal number.. Therefore create an algorithm and  C program to demonstrate how to convert a binary to octal.

Solution: An algorithm for this problem is represented in the following steps.

Algorithm: 

Step-1: Initially, the computer file permission is taken as input binary string.

Step-2: Assign the address of the first character of the string first using address (&) operator.

Step-3: Display the resulting string.

Code:

// C program to demonstrates conversion of binary to octal using approach-3
#include <stdio.h>
#include <math.h>

void File_Permisssion_binaryToOctal(long long aviation_code_binaryNumber, int *aviation_code_octalNumber);

int main() {
    long long aviation_code_binaryNumber;
    int aviation_code_octalNumber = 0;
    printf("Enter unix filepermission in binary string: ");
    scanf("%lld", &aviation_code_binaryNumber);
    File_Permisssion_binaryToOctal(aviation_code_binaryNumber, &aviation_code_octalNumber);
    printf("Equivalent octal number is: %d", aviation_code_octalNumber);
    return 0;
}

void File_Permisssion_binaryToOctal(long long aviation_code_binaryNumber, int *aviation_code_octalNumber) {
    int decimalNumber = 0, i = 0;
    while(aviation_code_binaryNumber != 0) {
        decimalNumber += (aviation_code_binaryNumber % 10) * pow(2, i);
        ++i;
        aviation_code_binaryNumber /= 10;
    }
    i = 1;
    while(decimalNumber != 0) {
        *aviation_code_octalNumber += (decimalNumber % 8) * i;
        decimalNumber /= 8;
        i *= 10;
    }
}

Output:

Enter unix file permission in binary string: 1101
Equivalent octal number is: 15

Code Explanation:

  • Preprocessor directives that include two header files, stdio.h and math.h.
  • We create a variable called File_Permisssion_binaryToOctal for user input and aviation_code_octal number for user output.
  •  Next we create a function called File_Permisssion_binaryToOctal() that takes two parameters. The first one is our input number (aviation_code_binaryNumber) and the second one is a pointer that points to our output variable location in the memory.
  •   As our execution starts with main function so we call  File_Permisssion_binaryToOctal()  function in our main, the working of aviation_code_binaryToOctal() is as follows:
  • In File_Permisssion_binaryToOctal() we initialize two variables i.e. decimal number and i and first we convert our aviation_code_binary number into decimal using while loop, so until our binary number becomes 0 we just we get the remainder of aviation_code_binary number and then multiply with pow(2,i) which will give us decimal number.
  • Next we convert decimal numbers into octal using our approach remainder, multiply and divide.

Conclusion

C programming language allows various number systems representations and their conversions using format specifiers and other approaches. A binary number may be converted into an octal number. Here, several approaches for converting a binary to octal number were presented with an algorithm, C program, output with its explanation. An address assignment approach is considered as the best approach because it offers a shortened and convenient way.