tags:

views:

199

answers:

2

i have an array (char data[16]) and i want to get data from user in hex digits so the array looks like :

 data[0]=0x887f76b1
 data[1]=0x8226baac
 ...

when the user input was : 887f76b18226baac ...

thank you very very much.

+2  A: 

Basically, you will want to read the first 8 characters of the string and convert them to a decimal format. There are utilities available for doing this. For example:

const char * data = "887f76b18226baac";
char buff[9] = {0};
unsigned long x = 0, y = 0;

sscanf(data, "%8s", buff);
x = strtoul(buff, NULL, 16);

sscanf(data + 8, "%8s", buff);
y = strtoul(buff, NULL, 16);

Realize that I elided all of the error checking there. Both sscanf and strtoul return error values (or provide mechanisms for checking for error). In cases where you are converting values it is wise to check for these error cases.

Edit: As mentioned in the comments, you will not be able to store these values in a char array. You will want to have an array of the proper data type (for my example you would use unsigned long array[16])

ezpz
The OP's example shows 8 hex digits being stored in each array location, for which unsigned long (and strtoul()) will suffice.
caf
Yes. long long is not always supported, right? unsigned long, OTOH is. Edited to use unsigned long.
ezpz
A: 

I think you want something along the lines of the following:

#include <stdio.h>
#include <string.h>

#define MAX_BUFFER 1024

int main(int argc, char **argv)
{
    char *input = "887f76b18226baac";
    unsigned char data[MAX_BUFFER];
    char tmp[3]; /* sue me for using magic numbers :) */
    int  i = 0, offset = 0;

    memset(data, 0, sizeof(data));

    while(sscanf(input + offset, "%2s", tmp) != EOF && i < MAX_BUFFER) {
     data[i++] = strtoul(tmp, NULL, 16);
     offset += 2;
    }
    return(0);
}

I'm assuming here that you absolutely need to store your input on a character array. If you wish to fit 0x887f76b1 into one array element, you'll need to use unsigned long, as ezpz suggested.

Michael Foukarakis