Huge thanks to our Platinum Members Endace and LiveAction,
and our Silver Member Veeam, for supporting the Wireshark Foundation and project.

Wireshark-dev: Re: [Wireshark-dev] bitmask handling in wireshark

From: Ed Beroset <beroset@xxxxxxxxxxxxxx>
Date: Tue, 28 Dec 2010 09:56:35 -0500 (GMT-05:00)
Andrei Emeltchenko wrote:
>I want to check what is the best way to convert code below to value_string

>
>				proto_tree_add_text(tree, tvb, offset, 1,
>						"%s%s%s%s",
>						(buf & 0x80)? "16kHz " : "",
>						(buf & 0x40)? "32kHz " : "",
>						(buf & 0x20)? "44.1kHz " : "",
>						(buf & 0x10)? "48kHz " : "");
>				proto_tree_add_text(tree, tvb, offset, 1,
>						"%s%s%s%s",
>						(buf & 0x08)? "Mono " : "",
>						(buf & 0x04)? "DualChannel " : "",
>						(buf & 0x02)? "Stereo " : "",
>						(buf & 0x01)? "JointStereo " : "");
>				offset++;

Here's how I'd do that.  First, the field definition (I'm only showing your first field):

#define MYPROTO_FLAG_SAMPLING 0xf0

static int hf_myproto_flags_sampling_rate = -1;

static const value_string myproto_sampling_rates[] = {
 { 0x01, "48kHz" },
 { 0x02, "44.1kHz" },
 { 0x04, "32kHz" },
 { 0x08, "16kHz" },
 { 0, NULL }
};


Then in your field definitions add this:

   { &hf_myproto_flags_sampling_rate,
    { "MyProto Sampling Rate", "myproto.flags.sampling_rate",
    FT_UINT8, BASE_HEX,
    VALS(myproto_sampling_rates), MYPROTO_FLAG_SAMPLING,
    NULL, HFILL }
   },
 

Finally, in the same place you'd have the code above, instead you would do this:
  
  proto_tree_add_item(flag_tree, hf_myproto_flags_sampling_rate, tvb, offset, 1, FALSE);
 
A few things to note here.  First, the values in the myproto_sampling_rates[] array are already shifted so although your original code uses 0x40 to identify a 32kHz rate, you'll see that this code uses 0x04.  That's deliberate and not a typo.  

Second, you'll see that I've added this item to a "flag_tree" variable.  This is a way to preserve the structure of the original packet by showing the individual subfields in a subtree.  For a complete example of this, see the tcp flags.

Ed