Ethereal-dev: Re: [Ethereal-dev] Can I use %hu, %hhu ??

Note: This archive is from the project's previous web site, ethereal.com. This list is no longer active.

From: Guy Harris <gharris@xxxxxxxxx>
Date: Thu, 06 Jan 2005 10:08:18 -0800
Stefano Pettini wrote:

According to README.developer, I should avoid using %lld, %llu, %llx, %llo in printf-like functions.
Can I use %hu, %hx, %hhu, %hhx to print guint16 and guint8 ??
As "h", unlike "ll", is in the ANSI C89 standard, it can be used - 
although, as the C89 standard indicates, arguments shorter than "int" or 
"unsigned int" are promoted to "int" or "unsigned int" when passed as 
one of the variable arguments to a varargs function, so I think the only 
reason why "h" is supported is to provide a syntactic similarity to 
scanf-like functions - i.e.:
	guint16 a;

	printf("%hx\n", a);

is the same as

	...

	printf("%x\n", a);

and "h" doesn't actually make any difference.

I don't see anything in the C89 standard mentioning "hh", so, unless I'm missing something, it's not portable. I don't know which implementations support it, so it probably shouldn't be used...
...but, again, guint8 arguments will be widened to "unsigned int", so 
"hh" doesn't actually make any difference.
If I have a buffer obtained through tvb_get_string, with a length unknown at compile time, how can I display these bytes in a protocol tree in hex? I can't use proto_tree_add_bytes.
If it was obtained through "tvb_get_string()", it's not an arbitrary 
array of bytes - the only byte with the value 0x00 will be the one that 
"tvb_get_string()" put at the end.
You can use proto_tree_add_bytes() to add to the protocol tree an item 
for a sequence of bytes even if the length isn't known at compile time, 
as long as you have a registered field to use with it - and, in fact, if 
you aren't going to be doing anything with those bytes other than 
putting them into the protocol tree to be displayed and to be available 
to filter on, you can just use proto_tree_add_item() - so presumably 
when you say that you can't use proto_tree_add_bytes() you mean that you 
don't have a registered field for those bytes.  If so, you can use 
bytes_to_str() to convert the array of bytes to a sequence of hex digits 
- or, if you're not doing anything with the bytes other than displaying 
them, you can use tvb_bytes_to_str().
If the value truly is just an array of bytes, you can use tvb_get_ptr() 
to get a pointer to them, rather than using tvb_get_string(), which does 
an extra g_malloc() and copy.