Hey Guys,

I am new to C programming and I got a task of storing hex dumps in character array and then use them as a string. I use the sprintf function for the job but it is giving me incorrect results. Please help me out. I am writing a prototype of the functionality I want to use.

#include<stdio.h>
int main()
{
	char a[25];
	int i;
	sprintf(a,"%d%d%d",0x0000001F,0x00000001,0x00271418);
	for(i=0;i<8;i++)
	{
		printf("\n%d",a[i]);
	}
	return 0;
}

"%d" will produce decimal. If you want hex then use "%x"

Try this:

int main()
{
	char a[25];
	int i;
	sprintf(a,"%x%x%x",0x0000001F,0x00000001,0x00271418);
	for(i=0;i<8;i++)
	{
		printf("%c\n",a[i]);
	}
	return 0;
}

I have tried it already. 1F should return the value 31 but instead it is returning 33. Same with all hex dumps. they all are returning incorrect results.

Change the %x to %d with the sprintf()
use %c when printing the chars

this code:

int main()
{
	char a[25];
	int i;
	sprintf(a,"%d%d%d",0x0000001F,0x00000001,0x00271418);
	for(i=0;i<8;i++)
	{
		printf("%c",a[i]);
	}
	return 0;
}

works fine for me..

sprintf() doesn't work that way. Each digit of the number will be placed in a different element of the character array. So for 0x1f the a[0] == '1' and a[1] == 'f' (assuming "%x")

#include<stdio.h>
int main()
{
    char a[25] = {0};
	int i;
    a[0] = 0x1f;
    a[1] = 0x01;
    a[2] = 0x00271418;
	//sprintf(a,"%4d%4d%4d",0x0000001F,0x00000001,0x00271418);
	for(i=0; i <3; i++)
	{
		printf("%d\n",a[i]);
	}
    return 0;
}
}

@AD:

But that's not what he wants right? I thought he wanted the decimal values of the hex numbers stored as a string in a char-array?
So my code should be OK

Change the %x to %d with the sprintf()
use %c when printing the chars

this code:

works fine for me..

But I think he was expending a[0] to be 31.

But I think he was expending a[0] to be 31.

Hmm. Let's ask:

@gargg321:

Do you want an array like this:
a[0] = 31
a[1] = 1
etc

or like this:
a[0] = '3'
a[1] = '1'
a[2] = '1'
etc

Guys I like the array to be of first option. I think the solution given by Ancient Dragon is OK with me but he is not using the sprintf function, instead he's given every element of array indidually. The string of hex dumps I have to use is real long and giving individual values is simply not possible. When I am using sprintf the problem still persists.

You didn't answer Niek's question. Which way do you expect to see the data ? If you want it similiar to what I posted then you can't use sprintf(). And the way I posted, one char can only hold a value up to 127 decimal (signed integer). If the values are larger than that then you can't do it my way.

I wanted the result in the first way but by using sprintf.

Be a part of the DaniWeb community

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