arrayscbit-manipulationbit-shiftbitwise-and

How I can convert 1byte of data into 2bytes of data


I want to convert 1byte of array element into 2 bytes E.g

arr[size] = {0x1F};

So, I want 0x1F will be stored in 2nd array like,

arr_2[size] = {0x01, 0x0f}

I have tried like following way...

for(i=j=0; j<2; i++){

arr_2[j]  =(0xF0 & arr[i]) >> 4;
arr_2[j++]=(0x0F & arr[i]);

}

Thanks in advance..!!


Solution

  • You were almost there, but didn't use the proper for() syntax to increment multiple iterators.

    Example:

    #define SIZE 1                      // for example, but the same principles 
                                        // would apply for malloc'd arrays
    unsigned char arr[SIZE] = {0x1F};   // 'SIZE' bytes
    unsigned char arr_2[SIZE * 2];      // You'll end up with twice as many bytes.
    
    
    // ...
    int i, j;
    
    // note how we test the input iterator (i) against the input size and how
    // the output iterator (j) is incremented by 2 on each iteration
    
    for (i = 0, j = 0; i < SIZE; i++, j += 2)
    {
        arr_2[j]     = (arr[i] & 0xF0) >> 4;
        arr_2[j + 1] = arr[i] & 0x0F;
    }