增加 十六进制字符串转 ByteArray

This commit is contained in:
luyao 2019-11-11 16:09:27 +08:00
parent 21d2e3f3ed
commit 35ba157e77
5 changed files with 50 additions and 8 deletions

View File

@ -103,7 +103,7 @@ publish {
userOrg = 'luyaox' //bintray.com
groupId = 'luyao.util.ktx' //访 jcenter上此项目的路径
artifactId = 'AndroidUtilKTX' //bintray.com Package
publishVersion = '0.0.7-alpha01' //
publishVersion = '0.0.7-alpha02' //
desc = 'Android Kotlin Util Code' //
website = 'https://github.com/lulululbj/AndroidUtilCodeKTX' //
}

Binary file not shown.

View File

@ -8,6 +8,7 @@ import android.graphics.PixelFormat
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import java.io.ByteArrayOutputStream
import java.util.*
/**
@ -31,6 +32,34 @@ fun ByteArray.toHexString(): String {
return String(result)
}
/**
* hex string to byte array
*/
fun String.hexToByteArray(): ByteArray {
var len = length
var hexString = this
if (len % 2 != 0) {
hexString = "0$hexString"
len++
}
val hexBytes = hexString.toUpperCase(Locale.getDefault()).toCharArray()
val ret = ByteArray(len shr 1)
var i = 0
while (i < len) {
ret[i shr 1] = ((hexBytes[i].hexToInt()) shl 4 or (hexBytes[i + 1].hexToInt())).toByte()
i += 2
}
return ret
}
fun Char.hexToInt(): Int {
return when (this) {
in '0'..'9' -> this - '0'
in 'A'..'F' -> this - 'A' + 10
else -> throw IllegalArgumentException()
}
}
/**
* byte array to int
*/

View File

@ -11,7 +11,7 @@ import java.io.File
*/
class AesExtKtTest {
private val plainText = "luyao"
private val plainText = "路遥.zip"
var key: ByteArray = ByteArray(128)
var iv: ByteArray = ByteArray(128)

View File

@ -10,15 +10,17 @@ import org.junit.Assert.*
*/
class TransformExtKtTest {
val integer = 207689539
val intBytes = byteArrayOf(12,97,23,67)
val short : Short = 32767
val shortBytes = byteArrayOf(-1,127)
private val text = "路遥.txt"
private val integer = 207689539
private val intBytes = byteArrayOf(12,97,23,67)
private val short : Short = 32767
private val shortBytes = byteArrayOf(-1,127)
val long = 2223372036854775807L
val longBytes = byteArrayOf(-1, -1, 67, 108, 22, 1, -37, 30)
private val long = 2223372036854775807L
private val longBytes = byteArrayOf(-1, -1, 67, 108, 22, 1, -37, 30)
@Test
fun test() {
@ -43,4 +45,15 @@ class TransformExtKtTest {
assertEquals(long,bytesToLong)
}
@Test
fun toHexString() {
val hexString = text.toByteArray().toHexString()
val originString = hexString.hexToByteArray()
assertEquals(text,String(originString))
}
}