Tigger12
Tigger12

Reputation: 53

How to Right Pad a Hexadecimal in C

So I know (after a lot of confusing google searching) that to right pad a string, one would use fprintf("%-10s", string), or something like that to pad with spaces up to 10 length.

So I have two questions:

I know that left-pad is similar, but what would the syntax for it be? (I'm sorry, I did google, but got confused by conflicting answers...)

And more importantly, how would I right-pad a hexidecimal? Say I have an int i want to convert to hex with %02X. Could I still use %-1002X ? Wouldn't that screw it up?

Upvotes: 0

Views: 2084

Answers (2)

AnT stands with Russia
AnT stands with Russia

Reputation: 320661

printf conversion formats allow you to either left-pad or right-pad the conversion result, but not both at the same time. Right-padding an integer conversion is the same as right padding anything else - just specify the negative field width, like %-10x. You cannot both left-pad and right-pad at the same time: you can only specify only one width in the format. Your original %02x is already explicitly using left padding. You cannot add right-padding on top of that.

However, it looks like the purpose of your %02x is to produce zero-padded output that has at least 2 digits. This can be achieved through using precision component of the format instead of using width. Format like %.2x will also successfully produce 2 digit hex conversion.

By using precision instead of width, you leave width available for padding purposes. E.g. format like %-10.2x will produce 2-digit conversions (padded with zeros) that are right padded with spaces to 10 characters.

Upvotes: 2

clearlight
clearlight

Reputation: 12625

try

printf("Hex %8.8x", someInt);

Or use fprintf(), sprintf(), snprintf(), whatever... If you're starting with a hex string, use snprintf() with the %-8s format specifier to capture the translation into a char * buffer, and then use a for loop or to substitute spaces with '0' characters.

Upvotes: 0

Related Questions