fprintf formatting

Hi,

I currently have a variable, foo, which represents either a hexadecimal number 16 bits wide or 17 bits wide. So foo can either look something like 0x1234 or 0x12345. I was wondering if it is possible set the formatting length to an integer instead of hardcoding either a 4 or 5. How do I do this? I know if I set the formatting length to 5 I will have a leading zero in the event that the hex number is 16 bits wide, but I would rather not have that.

Want something like:
1
2
3
int foo_length = foo_16_or_17_bit_length / 4;
if (foo_16_or_17_bit_length % 4 != 0){foo_length++;}
fprintf(myfile, "0x%[foo_length]x", foo);  //where foo is a hex number 16 or 17 bits long. 


instead of:
1
2
3
4
5
if(foo_length == 4){
fprintf(myfile, "0x%04x", foo);  //where foo is a hex number 16 bits long (e.g. 0x1234)
} else {
fprintf(myfile, "0x%05x", foo);  //where foo is a hex number 16 bits long (e.g. 0x12345)
}


Thanks in advance.
IIRC there's a * descriptor for that. I'm not sure exactly how it works. Might have to look it up in the documentation.

But I think it's something like this:

 
fprintf(myfile, "0x%0*x", foo_length, foo);


EDIT: wikipedia suggests I might have gotten it right, but I haven't actually tested it. Give it a whirl and see how it goes.

EDIT 2:

Also, you can ditch the if statement and do a simple round up with addition:

1
2
3
4
5
6
// blech
int foo_length = foo_16_or_17_bit_length / 4;
if (foo_16_or_17_bit_length % 4 != 0){foo_length++;}

//yay
int foo_length = (foo_16_or_17_bit_length + 3) / 4;
Last edited on
Topic archived. No new replies allowed.