Skip to content

Commit 3a5a198

Browse files
committed
Handle even hex strings while converting to ByteArray
1 parent f1e0c4d commit 3a5a198

File tree

1 file changed

+12
-8
lines changed
  • ethereumkit/src/main/java/io/horizontalsystems/ethereumkit/core

1 file changed

+12
-8
lines changed

ethereumkit/src/main/java/io/horizontalsystems/ethereumkit/core/Extensions.kt

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -24,24 +24,28 @@ fun ByteArray?.toHexString(): String {
2424

2525
@Throws(NumberFormatException::class)
2626
fun String.hexStringToByteArray(): ByteArray {
27-
val hexWithoutPrefix = this.stripHexPrefix()
28-
return ByteArray(hexWithoutPrefix.length / 2) {
29-
hexWithoutPrefix.substring(it * 2, it * 2 + 2).toInt(16).toByte()
30-
}
27+
return this.getByteArray()
3128
}
3229

3330
@Throws(NumberFormatException::class)
3431
fun String.hexStringToByteArrayOrNull(): ByteArray? {
3532
return try {
36-
val hexWithoutPrefix = this.stripHexPrefix()
37-
ByteArray(hexWithoutPrefix.length / 2) {
38-
hexWithoutPrefix.substring(it * 2, it * 2 + 2).toInt(16).toByte()
39-
}
33+
this.getByteArray()
4034
} catch (error: Throwable) {
4135
null
4236
}
4337
}
4438

39+
private fun String.getByteArray(): ByteArray {
40+
var hexWithoutPrefix = this.stripHexPrefix()
41+
if (hexWithoutPrefix.length % 2 == 1) {
42+
hexWithoutPrefix = "0$hexWithoutPrefix"
43+
}
44+
return ByteArray(hexWithoutPrefix.length / 2) {
45+
hexWithoutPrefix.substring(it * 2, it * 2 + 2).toInt(16).toByte()
46+
}
47+
}
48+
4549
fun String.stripHexPrefix(): String {
4650
return if (this.startsWith("0x", true)) {
4751
this.substring(2)

0 commit comments

Comments
 (0)