Link to home
Start Free TrialLog in
Avatar of Jax Logan
Jax Logan

asked on

Converting UINT array of binary data to hex (C Programming)

Hi,

I've got an array of unsigned int binary characters that I would like to convert to an array of uint hex characters.

is there a standard C function for this or would I need to write one my own (and how could that look like)?

Thanks!
Avatar of phoffric
phoffric

If I understand you correctly, you have:

  unsigned char cbin[100]; // filled with 100 values

and you want:

  unsigned int ibin[100];   // filled with equivalent 100 values

Then just have a for-loop
  for(int i=0; i<100; ++i) {
     ibin[i] = cbin[i];
  }
here...this link will definitelty help you

http://www.cplusplus.com/reference/clibrary/cstdlib/itoa/

the function is itoa, which converts an integer into a string, you can pass the 3rd argument as 16 to get hex values, you'll have to go through the array and convert everything.. use strcat to append each character into a string or char array.

Now that for-loop puts one char binary value into one int value. Perhaps you want to pack 4 char binary values into one int value?

One way:
  unsigned int ibin[25];   // filled with equivalent 25*4 = 100 char values

  for(int i=0; i<25; ++i) {
     memcpy( ibin[i], cbin[4*i], 4 );
  }
 
That packs it, but is it what you want? There are endian issues to consider.
If you have no endian issues, then you can use a union like this:

union pack{
  unsigned char cbin[100]; // filled with 100 char values
  unsigned int ibin[25];
};
main(){
   unsigned int a[5] = { 0xAAFFCCDD, 0xBBEEDDCC, 0xCCDDEEFF, 0x55443322, 0x11223344 };
   for(int j=0; j<5; j++){
      char b[10];
      itoa(a[j],b,16);
      printf("%s\n",b);
      }
}

output:
aaffccdd
bbeeddcc
ccddeeff
55443322
11223344


if that's what you're looking for.
ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Jax Logan

ASKER

worked for me - thanks!