hi all.

the following is working fine for me
char * hex = (..dynamically allocated memory with malloc..);

*(hex+0) = 0x43;
*(hex+1) = 0x2b;

i now have to assign a string in the format 43 2b 1c to the char * array at runtime.
anyone did it ?
plz guide.

## All 7 Replies

I (and probably others too) don't fully understand your problem. How can the following be "working fine" for you?
char * hex = (..dynamically allocated memory with malloc..);

And you haven't explained your problem well enough, either. Here's what i understood it as:
You have two character arrays-str1 and str2. One has hexadecimal numbers in it(43 2b 1c). Now you have to copy it's contents to str2 by as hexadecimal values. Is that correct?

ok let me simplify the problem.
0x54 is hex of T.
If u run the following it prints "x= T" on the screen.
char x;
x=0x54;
printf("x = %c\n",x);

now the prob is if u already have a string like
0x54 0x78 0x2d in a text file how to store each of the hex in a char.

when u read this string in a char array it will be represented as
0|x|5|4| |0|x|7|8| |0|x|2|d|
a char array of 14+1.
Any idea how to store 0|x|5|4| in 1 char ?

The %x format specifier (for scanf() and related functions) reads a hex value (with the 0x prefix) and stores it in an int. If that integer is within the range of values that can be stored in a char, convert it to char. Otherwise report an error.

The only other bit you need to worry about is the 0x prefix in your file. You can work out for yourself what to do with those characters.

the 0x part must be removed or not ?

u said for scanf() reads the prefix.

If you're reading from a text file, you can use fscanf() to read in the numbers. And it's not necessary to prefix the numbers with a 0x, although for convenience's sake, you can.

Ex: Let's say your text file looks like this:

``````54
4B
3a``````

You can read them from the text file as such:

``````int main()
{
int hex;
FILE* fp;
fp = fopen("hex.txt","r");
while(fscanf(fp,"%x",&hex)==1)
{
printf("%d\t%x\t%c\n",hex,hex,hex);
}
fclose(fp);
getchar();
return 0;
}``````