Help using sprintf, wanting to make 2 byte lengths and 4 byte lengths to hex string?

J

jt

Here is my code:

unsigned long listenip;
short tlen;

sprintf(tmp,"len:%x listenip:%x",htonl(tlen),listenip);

If the value on "tlen" is less than 2 bytes and the value on "listenip" is
less than 4 bytes, how can I make it fill with preciding 0 zeros?

Thanks,
JT
 
B

baumann@pan

jt said:
Here is my code:

unsigned long listenip;
short tlen;

sprintf(tmp,"len:%x listenip:%x",htonl(tlen),listenip);
since tlen is less than 2 bytes, you should use htons() instead.

sprintf(tmp,"len:%02x listenip:%04x",htonl(tlen),listenip);
above should work for your purpose.
 
D

Dave Thompson

since tlen is less than 2 bytes, you should use htons() instead.
is _exactly_ 2 bytes, on "normal" systems with 8-bit byte and 16-bit
short, which is not absolutely everywhere but does include the places
sockets functions like these (and maybe Unix I/O in general) are
likely to be available and work as expected.
sprintf(tmp,"len:%02x listenip:%04x",htonl(tlen),listenip);
above should work for your purpose.
htons, as you said; and %04lx (ell ecks) for the listenip; x with no
modifier expects and prints unsigned int which can be as little as 16
bits (2 bytes) and is on some systems, at least one of them socketed.

- David.Thompson1 at worldnet.att.net
 
K

Keith Thompson

Dave Thompson said:
On 17 May 2005 18:03:40 -0700, "baumann@pan" <[email protected]>
wrote: [...]
since tlen is less than 2 bytes, you should use htons() instead.
is _exactly_ 2 bytes, on "normal" systems with 8-bit byte and 16-bit
short, which is not absolutely everywhere but does include the placesn
sockets functions like these (and maybe Unix I/O in general) are
likely to be available and work as expected.

I've used Unix systems where short is 32 bits, and others where it's
64 bits (both Crays). Along with CHAR_BIT==8 and the lack of extended
integer types, this implies that there is no 16-bit integer type,
which makes some of the network stuff interesting (it uses bit
fields).
 

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

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,015
Latest member
AmbrosePal

Latest Threads

Top