• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 842
  • Last Modified:

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!
0
php-newbie
Asked:
php-newbie
1 Solution
 
phoffricCommented:
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];
  }
0
 
vidularandunuCommented:
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.

0
 
phoffricCommented:
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];
};
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
vidularandunuCommented:
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.
0
 
jkrCommented:
If you want to convert integers to their hexadecimal representation, the result is text - if that is what you want, you could do that like
#include <stdio.h>

unsigned int numbers[100];
char hex[100][9]; // room for 8 chars and the terminating NULL

// fill 'numbers'

// convert:

for (int i = 0; i < 100; ++i) {

  sprintf(hex[i],"%x",numbers[i]); // '%x' will format as hex
}

Open in new window

0
 
php-newbieAuthor Commented:
worked for me - thanks!
0

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now