1

I have an array of char but values is decimal representation of a character. example:

char bytes[4]={50,48,49,51}
how to convert this to get char array like this:

char bytes1[4]={2,0,1,3}
c

The quick and dirty solution is to substract 48. Could be a for loop that iterates over the bytes[] array.

if you want to convert it to array of int:

#include <iostream>

using namespace std;

int main()
{
    char bytes[4]={50,48,49,51};
    int bytes1[4];
    for (int i = 0; i < 4; i++)
        bytes1[i] = (bytes[i] - 48) ;
    for (int i = 0; i < 4; i++)
        cout << bytes1[i] << ' ';

    return 0;
}

if you want it as array of char:

int main()
{
    char bytes[4]={50,48,49,51};
    char bytes1[4];
    for (int i = 0; i < 4; i++)
        bytes1[i] = (bytes[i] - 48) + 48;
    for (int i = 0; i < 4; i++)
        cout << bytes1[i] << ' ';

    return 0;
}

this simple implementation base on ASCII code values

The quick and dirty solution of subtracting 48 (or 0x30 if we're talking hexadecimal) will work. However, for multi-character values, if your sequence of characters is null-terminated (as it should be), the better way is to use sscanf from the <cstdio> library.

The C version would be:

#include <stdio.h>

int main() {
    char bytes[4] = {50, 48, 49, 51};
    int bytes1[4];

    for (int i = 0; i < 4; i++) {
        bytes1[i] = bytes[i] - '0';
    }

    for (int i = 0; i < 4; i++) {
        printf("%d ", bytes1[i]);
    }

    return 0;
}

2 0 1 3

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.