Convert ASCII string (char[]) to octal string (char[]) in C

C | Convert ASCII string to octal string: Here, we are going to learn how to convert a given string (that contains ascii characters) to its equivalent octal string in C? By IncludeHelp Last updated : April 20, 2023

Given an ASCII string (char[]) and we have to convert it into octal string (char[]) in C.

Logic to convert an ASCII string to octal string

To convert an ASCII string to octal string, follow below-mentioned steps:

  • Extract characters from the input string and convert the character in octal format using %02o format specifier, %02o gives 0 padded two bytes octal value of any value (like int, char).
  • Add these two bytes (characters) which is a octal value of an ASCII character to the output string.
  • After each iteration increase the input string's loop counter (loop) by 1 and output string's loop counter (i) by 2.
  • At the end of the loop, insert a NULL character to the output string.

Example

Input: "Hello world!"
Output: "111415151540161516151441"

C program to convert ASCII char[] to octal char[]

In this example, ascii_str is an input string that contains "Hello world!", we are converting it to a octal string. Here, we created a function void string2OctalString(char* input, char* output), to convert ASCII string to octal string, the final output string is storing in oct_str variable.

#include <stdio.h>
#include <string.h>

//function to convert ascii char[] to octal-string (char[])
void string2OctalString(char* input, char* output)
{
    int loop;
    int i;

    i = 0;
    loop = 0;

    while (input[loop] != '\0') {
        sprintf((char*)(output + i), "%02o", input[loop]);
        loop += 1;
        i += 2;
    }
    //insert NULL at the end of the output string
    output[i++] = '\0';
}

int main()
{
    char ascii_str[] = "Hello world!";
    //declare output string with double size of input string
    //because each character of input string will be converted
    //in 2 bytes
    int len = strlen(ascii_str);
    char oct_str[(len * 2) + 1];

    //converting ascii string to octal string
    string2OctalString(ascii_str, oct_str);

    printf("ascii_str: %s\n", ascii_str);
    printf("oct_str: %s\n", oct_str);

    return 0;
}

Output

ascii_str: Hello world!
oct_str: 111415151540161516151441



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.