I am developing an Android NFC application. This application can scan an NFC tag (here I have an NXP NTAG 5 boost tag, which is an NFC Forum Type 5 tag).
Since the UID of the NFC-V tag is reversed, my goal is to display the (re)reversed UID of the NFC tag, where each byte is separated by two dots.
Below is the method I use to do this. It reverses the UID well and converts it to hexadecimal well but I can't figure out how to insert a ":" separator every other character.
fun byteArrayToHexInversed(bytes: ByteArray): String {
//First reverse the UID
bytes.reverse()
//Then convert byteArray to Hexa
val hexChars = CharArray(bytes.size * 2)
for (j in bytes.indices) {
val v = bytes[j].toInt() and 0xFF
hexChars[j * 2] = hexArray[v ushr 4]
hexChars[j * 2 + 1] = hexArray[v and 0x0F]
}
//Finally return the String with the separators
return hexChars.joinToString(":") { byte ->
byte.toString().padStart(2, '0')
}
}
Here is what I have in input:
000839CB580104E0
Here is what I want in output:
E0:04:01:58:CB:39:08:00
I don't know how wild for efficiency you are with this, but here's an approach!
var input = "000839CB580104E0"
input.chunked(2).reversed().joinToString(":").run(::println)
>> E0:04:01:58:CB:39:08:00
It's basically splitting your input into a list of two-character chunks (so they keep their order, e.g. E0
), then reversing that list (so the chunks themselves aren't reversed, but they're listed in reverse order) and you know the rest!
If you want something more efficient with indices, you could do the same thing going over an array in reverse order, grabbing characters in pairs
I can't get your hexChars.joinToString { byte conversion }
stuff to work with that input, so I'm probably not setting up hexChars
right - I'm just assuming you can start with a String
version here, e.g. by calling joinToString(separator="")
on the CharArray
If you want to work on the array directly, you can call asIterable()
on it:
input.asIterable()
.chunked(2) { it.joinToString(separator="") }
.reversed()
.joinToString(":")
.run(::println)
but you'll still need to combine each pair of chars into a string at some point, which is what that transform lambda is doing. joinToString
takes a transform function to, so you could do it there instead if you like