Last active
May 11, 2021 11:24
-
-
Save groovelab/38d381a943556299f205b47307bf60d7 to your computer and use it in GitHub Desktop.
Kotlinの各型とByte配列の相互変換
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// [0x00, 0xff] -> "00ff" | |
fun ByteArray.toHexString(asReverse: Boolean = false): String = | |
map { String.format("%02x", it) } | |
.let { if (asReverse) it.asReversed() else it } | |
.joinToString("") | |
// 2byte (Little Endian) | |
fun ByteArray.toShort(): Short { | |
var result: Int = 0 | |
for (i in 0 until count()) { | |
result = result or (get(i).toUByte().toInt() shl 8 * i) | |
} | |
return result.toShort() | |
} | |
// 4byte (Little Endian) | |
fun ByteArray.toInt(): Int { | |
var result: Int = 0 | |
for (i in 0 until count()) { | |
result = result or (get(i).toUByte().toInt() shl 8 * i) | |
} | |
return result | |
} | |
// 8byte (Little Endian) | |
fun ByteArray.toLong(): Long { | |
var result: Long = 0 | |
for (i in 0 until count()) { | |
result = result or (get(i).toUByte().toLong() shl 8 * i) | |
} | |
return result | |
} | |
// 4byte (Little Endian) | |
fun ByteArray.toFloat() = intBitsToFloat(toInt()) | |
// 8byte (Little Endian) | |
fun ByteArray.toDouble() = longBitsToDouble(toLong()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// "00ff" -> [0x00, 0xff] | |
fun String.asByteArray(): ByteArray { | |
val hexString = if (length % 2 == 0) this else "0${this}" | |
return hexString.chunked(2).map { it.asByte() }.toByteArray() | |
} | |
// "00" -> [0x00] | |
fun String.asByte() = substring(0, 2).toShort(16).toByte() | |
// 2byte (Little Endian) | |
fun Short.toBytes(): ByteArray { | |
var l = this.toInt() | |
val result = ByteArray(2) | |
for (i in 0..1) { | |
result[i] = (l and 0xff).toByte() | |
l = l shr 8 | |
} | |
return result | |
} | |
// 4byte (Little Endian) | |
fun Int.toBytes(): ByteArray { | |
var l = this | |
val result = ByteArray(4) | |
for (i in 0..3) { | |
result[i] = (l and 0xff).toByte() | |
l = l shr 8 | |
} | |
return result | |
} | |
// 8byte (Little Endian) | |
fun Long.toBytes():ByteArray { | |
var l = this | |
val result = ByteArray(8) | |
for (i in 0..7) { | |
result[i] = (l and 0xFF).toByte() | |
l = l shr 8 | |
} | |
return result | |
} | |
// 4byte (Little Endian) | |
fun Float.toBytes() = toRawBits().toBytes() | |
// 8byte (Little Endian) | |
fun Double.toBytes() = toRawBits().toBytes() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment