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.

Recommended Answers

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;
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 ?

Your first problem description had almost no relationship to your second.

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:


You can read them from the text file as such:

int main()
    int hex;
    FILE* fp;
    fp = fopen("hex.txt","r");
    return 0;

I hope that's what you had asked for.

thx for the code , but i wanted to read & store each of the hex values (e.g 54 - hex of T) in 1 char so that when i print the char it gives me back T as output.

Then modify the sample code he gave you. Programming is an adventure, TRY something and see what it does (especially on simple things like this).

If you try something and it doesn't do what you want, either modify it and try again, or post it here with a 'it does ___, but I wanted ___' or a 'Why does this code do ____ I thought it would do ___' type of question.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.