Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a byte array into a hex string

Surprisingly (to me), this code does not do what I want:

fun ByteArray.toHexString() : String {
    return this.joinToString("") { it.toString(16) }
}

Turns out Byte is signed, so you get negative hex representations for individual bytes, which leads to a completely bogus end result.

Also, Byte.toString won't pad leading zeroes, which you'd want here.

What is the simplest (no additional libraries, ideally no extensions) resp. most efficient fix?

like image 505
Raphael Avatar asked Sep 07 '18 15:09

Raphael


People also ask

Can you convert byte into string?

One method is to create a string variable and then append the byte value to the string variable with the help of + operator. This will directly convert the byte value to a string and add it in the string variable. The simplest way to do so is using valueOf() method of String class in java.

How do you convert bytes to hex in python?

Use the hex() Method to Convert a Byte to Hex in Python The hex() method introduced from Python 3.5 converts it into a hexadecimal string. In this case, the argument will be of a byte data type to be converted into hex.

How do you write a byte in hexadecimal?

The basic level at which the electronic circuitry in a computer works - a single bit. Each Hexadecimal character represents 4 bits (0 - 15 decimal) which is called a nibble (a small byte - honest!). A byte (or octet) is 8 bits so is always represented by 2 Hex characters in the range 00 to FF.


Video Answer


2 Answers

As I am on Kotlin 1.3 you may also be interested in the UByte soon (note that it's an experimental feature. See also Kotlin 1.3M1 and 1.3M2 announcement)

E.g.:

@ExperimentalUnsignedTypes // just to make it clear that the experimental unsigned types are used
fun ByteArray.toHexString() = asUByteArray().joinToString("") { it.toString(16).padStart(2, '0') }

The formatting option is probably the nicest other variant (but maybe not that easily readable... and I always forget how it works, so it is definitely not so easy to remember (for me :-)):

fun ByteArray.toHexString() = joinToString("") { "%02x".format(it) }
like image 83
Roland Avatar answered Oct 19 '22 18:10

Roland


printf does what we want here:

fun ByteArray.toHexString() : String {
    return this.joinToString("") {
        java.lang.String.format("%02x", it)
    }
}
like image 10
Raphael Avatar answered Oct 19 '22 20:10

Raphael