问题
I'm using the MFRC522 library on my Arduino UNO to read Mifare RFID tag Info.
// Print HEX UID
Serial.print("Card UID:");
for (byte i = 0; i < mfrc522.uid.size; i++) {
Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
Serial.print(mfrc522.uid.uidByte[i], HEX);
}
Serial.println();
I've got a byte array(4) which contains the HEX UID:
54 C7 FD 5A
But I've failed to convert it to Decimal:
HEX(5AFDC754) => DEC(1526581076)
I've tried to convert the byte array to char reversely, but the compiler didn't let me print Dec.
char str[8];
int k = 0;
for (int i = 3; i >= 0 ; i -= 1) {
char hex[4];
snprintf(s, 4, "%x", mfrc522.uid.uidByte[i]);
for( int t = 0; t < 4; t++ ) {
if( (int)hex[t] != 0 )
str[t+k] = hex[t];
}
k+=2;
}
Serial.println( str, DEC);
Any suggestion is appreciated
回答1:
You will need to combine the 4 hex bytes into a single unsigned integer.
This depends on Endianess (search for it).
For Big Endian:
unsigned int hex_num;
hex_num = uidByte[0] << 24;
hex_num += uidByte[1] << 16;
hex_num += uidByte[2] << 8;
hex_num += uidByte[3];
For Little Endian, reverse the order of uidByte positions.
来源:https://stackoverflow.com/questions/21678099/convert-mfrc522-uid-hex-bytes-to-printable-decimal