tairon tairon - 21 days ago 5
C Question

Four 1byte char to One 4byte int?

I have an char array of 1000 bytes. I want to convert it into int array such that four elements of char array (each of one byte) is equal to one element of int array (each of four bytes).

e.g.:
char_array[0] = '0'
char_array[1] = '9'
char_array[2] = '2'
char_array[3] = '8'

it should be converted to
int_array[0] = 928 or 0928.


How should I do that?

Answer

Try following code:

#include<iostream>
#include<cstring>

using namespace std;

#define CHAR_ARRAY_SIZE 8

int main()
{
    char charArray[CHAR_ARRAY_SIZE] = {'1', '2', '3', '4', '5', '6', '7', '8'};

    int intArray[2];
    for(int i = 0; i < CHAR_ARRAY_SIZE/4; i++) {
        char ch1 = (charArray[4*i+0] - '0');
        char ch2 = (charArray[4*i+1] - '0');
        char ch3 = (charArray[4*i+2] - '0');
        char ch4 = (charArray[4*i+3] - '0');

        intArray[i] = ch1*1000 + ch2*100 + ch3*10 + ch4;
    }
    cout << "intArray[0] : " << intArray[0] << endl;
    cout << "intArray[1] : " << intArray[1] << endl;

    return 0;
}