How does this code snippet work?

for (byte i = 0; i < uid->size; i++) {
	Serial.print(uid->uidByte[i] < 0x10 ? " 0" : " ");
	Serial.print(uid->uidByte[i], HEX);
	}

This is taken from the MFRC522 library by miguelbalboa.
The first Serial.print with the ternary condition is what I can't understand.
The output from this operation is formatted #### #### #### ####.
Since the first operation prints a space every iteration regardless of data, why are there only spaces every four bytes?

Edit 1: uidByte is "byte uidByte[10]" and "uid->size" is an int of 4,7, or 10.

By default, the print method doesn't print leading zeroes in any base, so 0x09 would be printed as '9'

The first Serial.print with the ternary condition is what I can't understand.

If the value being printed is < 10 print a '0' before printing the value.

Since the first operation prints a space every iteration regardless of data,

No it doesn't, see previous paragraph. Only ABCDEF hex values will print a space. Strike that, I just noticed the space in front of the 0.

On the surface that looks like a bug, I think it should print nothing if the value is > 9. But I don't know the context of this function.

EDIT: It seems that all bytes should have a space inserted, as this is an ID being printed maybe the author is relying on knowledge of the constituent byte values to insert spaces to make it more readable, IE he knows that every 4th value is > 10 and all the others are < 10. What are some typical values?

Bugger, I just noticed it's < 0x10 not < 10, don't pay me no mind :slight_smile:


Rob

Ok I feel like an idiot.

AWOL was correct, I just misinterpreted what was being printed.

In case anyone else gets stumped by this here's what's happening:

If you try to print 0x01 Serial.print will only print "1".

If the value is less than 0X10 (or 16 in decimal) then the value will be 0x0#, and the 0 will be dropped. The tertiary operator catches that and prints "0" manually. It's a brute-force way to display the full hex byte.

If the value to be printed is going to have two non-zero numbers, the tertiary operation simply prints a space, and lets the second Serial.print print both characters. So the first line would print " " and the second line would print "FF"