Home > OS >  How I can convert 1byte of data into 2bytes of data
How I can convert 1byte of data into 2bytes of data

Time:02-03

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 is advance..!!

CodePudding user response:

In fact you are doing all correctly except the for loop statement

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

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

}

in the body of which you are setting at least the same element of the array arr_2 twice.

It is redundant.

You could just write

arr_2[0]  =(0xF0 & arr[0]) >> 4;
arr_2[1] = 0x0F & arr[0];

CodePudding user response:

To build on Vlad's answer, maybe you used a loop because you really want to expand n bytes into n*2 bytes.

for ( size_t i = 0; i < n;   i ) {
   dst[ i*2 0 ] = ( src[ i ] >> 4 ) & 0xF;
   dst[ i*2 1 ] = ( src[ i ] >> 0 ) & 0xF;
}

or

for ( size_t j = 0, i = 0; i < n;   i ) {
   dst[ j   ] = ( src[ i ] >> 4 ) & 0xF;
   dst[ j   ] = ( src[ i ] >> 0 ) & 0xF;
}

CodePudding user response:

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] & 0x0F) >> 4;
    arr_2[j   1] = arr[i] & 0x0F;
}

CodePudding user response:

You don't need to maintain two index variables. Here is a solution assuming you want to store the elements in an array of twice the length of the source array:

#include <stdio.h>

#define LEN(arr) (sizeof (arr) / sizeof (arr)[0])

int main(void)
{
    unsigned char arr[] = {0x1f, 0x2f, 0x3f, 0x4f};
    unsigned char arr_2[2 * LEN(arr)];
    size_t i;

    for (i = 0; i < LEN(arr); i  ) {
        arr_2[2 * i] = arr[i] >> 4;
        arr_2[2 * i   1] = arr[i] & 0x0f;
    }
    for (i = 0; i < LEN(arr_2); i  ) {
        printf("%x", arr_2[i]);
    }
    printf("\n");
    return 0;
}

Output:

1f2f3f4f
  • Related