C Tutorial

C Basics

C Data Types

C Input/Output

C Operators

C Conditional Statements

C Control Statements

C Strings

C Functions

C Arrays

C Structure and Unions

C Pointers

C Preprocessor Directives

C Command-line Arguments

C File Handlings

C Graphics

C Advance Topics

C Tips and Tricks

C Important Topics

C Practice

Convert ASCII string (char[]) to BYTE array in C

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

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

Logic to convert an ASCII string to BYTE array

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

  • Extract characters from the input string and get the character's value in integer/number format using %d format specifier, %d gives integer (number) i.e. BYTE value of any character.
  • Add these bytes (number) which is an integer value of an ASCII character to the output array.
  • After each iteration increase the input string's loop counter (loop) by 1 and output array's loop counter (i) by 1.


Input: "Hello world!"

C program to convert ASCII char[] to BYTE array

In this example, ascii_str is an input string that contains "Hello world!", we are converting it to a BYTE array. Here, we created a function void string2ByteArray(char* input, BYTE* output), to convert ASCII string to BYTE array, the final output (array of integers) is storing in arr variable, which is passed as a reference in the function.

Note: Here, we created a typedef BYTE for unsigned char data type and as we know an unsigned char can store value from 0 to 255.

Read more: typedef in C, unsigned char in C

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

typedef unsigned char BYTE;

//function to convert string to byte array
void string2ByteArray(char* input, BYTE* output)
    int loop;
    int i;

    loop = 0;
    i = 0;

    while (input[loop] != '\0') {
        output[i++] = input[loop++];

int main()
    char ascii_str[] = "Hello world!";
    int len = strlen(ascii_str);
    BYTE arr[len];
    int i;

    //converting string to BYTE[]
    string2ByteArray(ascii_str, arr);

    printf("ascii_str: %s\n", ascii_str);
    printf("byte array is...\n");
    for (i = 0; i < len; i++) {
        printf("%c - %d\n", ascii_str[i], arr[i]);

    return 0;


ascii_str: Hello world!
byte array is...
H - 72
e - 101
l - 108
l - 108
o - 111
  - 32 
w - 119
o - 111
r - 114
l - 108
d - 100
! - 33

Comments and Discussions!

Load comments ↻

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