sprintf: the format problem

H

Huey

Hi All,

I saved hashed values of hex into buf[32], then buf becomes unreadable
by the means of calling puts(buf), printf("%s") and so on. Then, I
need to convert the hex in buf[] into a char buffer cbuf[32], by
calling sprintf(). I did:

sprintf(cbuf, "%x", buf);

No error! Just no working. Well, I used sprintf() a lot in format "%s"
"%d", and liked sprintf. It is my first time of using it in format
"%x". I wonder does format affect sprintf? Anybody can help me to get
this trick? Thanks!

Huey
 
K

Kevin Goodsell

Huey said:
Hi All,

I saved hashed values of hex into buf[32], then buf becomes unreadable
by the means of calling puts(buf), printf("%s") and so on. Then, I
need to convert the hex in buf[] into a char buffer cbuf[32], by
calling sprintf(). I did:

sprintf(cbuf, "%x", buf);

I understand very little of what you've said, but if buf is an array
then you certainly cannot use it this way in a sprintf call. The %x
format specifier applies *ONLY* to unsigned int. If you pass anything
else, the behavior is undefined.

I would try to suggest an alternative, but I have no idea what you are
trying to do.

-Kevin
 
R

Robert Stankowic

Huey said:
Hi All,

I saved hashed values of hex into buf[32], then buf becomes unreadable
by the means of calling puts(buf), printf("%s") and so on. Then, I
need to convert the hex in buf[] into a char buffer cbuf[32], by
calling sprintf(). I did:

sprintf(cbuf, "%x", buf);

Try
(CHAR_BIT == 8 assumed)

#include <stdlib.h>
#include <stdio.h>

int main(void)
{
int i;
unsigned char buf[32] =
{0, 1, 2, 3, 4, 5, 55, 66, 77};
char cbuf[97];

for(i = 0; i < 32; i++)
{
sprintf(cbuf + 3 * i, "%02x ", buf);
}
puts(cbuf);
return EXIT_SUCCESS;
}

No error! Just no working. Well, I used sprintf() a lot in format "%s"
"%d", and liked sprintf. It is my first time of using it in format
"%x". I wonder does format affect sprintf? Anybody can help me to get
this trick? Thanks!

from N869:
o,u,x,X The unsigned int argument is converted to unsigned octal (o),
unsigned
decimal (u), or unsigned hexadecimal notation (x or X) in the style dddd;
the
letters abcdef are used for x conversion and the letters ABCDEF for X
conversion. The precision specifies the minimum number of digits to appear;
if the value being converted can be represented in fewer digits, it is
expanded
with leading zeros. The default precision is 1. The result of converting a
zero value with a precision of zero is no characters.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,821
Latest member
AleidaSchi

Latest Threads

Top