Last active
October 14, 2019 17:35
-
-
Save zion830/48342b4d71853ce1a367eaf3ab35a71d to your computer and use it in GitHub Desktop.
big-endian, little-endian 변환하는 예제
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
import kotlin.experimental.and | |
object EndianConverter { | |
fun printConvertResult(testValue: Array<Long>) { | |
for (number in testValue) { | |
println("Input Value : 0x${Integer.toHexString(number.toInt())}") | |
val littleEndianArray = convertEndianSystem(number) | |
val littleEndianIntValue = bytesToInt(littleEndianArray) | |
val bigEndianArray = convertEndianSystem(littleEndianIntValue.toLong()) | |
println("Little : ${bytesToStr(littleEndianArray)}") | |
println("Little system print out in 0x${Integer.toHexString(littleEndianIntValue)}") | |
println("\nBig : ${bytesToStr(bigEndianArray)}") | |
println("Big system print out in 0x${Integer.toHexString(bytesToInt(bigEndianArray))}") | |
println("--------------------------------------------") | |
} | |
} | |
// byteArray의 값을 16진수 형식의 문자열로 변환한다 | |
private fun bytesToStr(byteArray: ByteArray): String { | |
val builder = StringBuilder() | |
for (i in byteArray.indices) { | |
builder.append(String.format("ch[%d]=%02x ", i, byteArray[i])) | |
} | |
return builder.toString() | |
} | |
// byteArray를 정수로 변환한다 | |
private fun bytesToInt(byteArray: ByteArray): Int { | |
var result = byteArray[3].toInt() and 0xFF | |
result = result or (byteArray[2].toInt() shl 8) | |
result = result or (byteArray[1].toInt() shl 16) | |
result = result or (byteArray[0].toInt() shl 24) | |
return result | |
} | |
// 엔디안 시스템에 따라 값의 자리를 변경한다 | |
private fun convertEndianSystem(value: Long): ByteArray = byteArrayOf( | |
value.toByte(), // 바이트로 변환하면서 나머지 앞쪽 비트는 제거함 | |
(value shr 8).toByte(), | |
(value shr 16).toByte(), | |
(value shr 24).toByte() | |
) | |
} |
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
import EndianConverter.printConvertResult | |
fun main(args: Array<String>) { | |
val testValue = arrayOf( | |
0x12345678, | |
0x12345680, | |
0x82345678 | |
) | |
printConvertResult(testValue) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment