This language bar is your friend. Select your favorite languages!
Select your favorite languages :
- Or search :
Idiom #175 Bytes to hex string
From the array a of n bytes, build the equivalent hex string s of 2n digits.
Each byte (256 possible values) is encoded as two hexadecimal characters (16 possible values per digit).
- C
- C#
- C#
- D
- Dart
- Erlang
- Fortran
- Go
- Go
- Groovy
- JS
- JS
- Java
- Java
- Java
- Lisp
- Lua
- Pascal
- Perl
- Python
- Ruby
- Ruby
- Rust
- Rust
- Rust
- Rust
String s = range(0, n)
.mapToObj(x -> a[x])
.map("%02x"::formatted)
.reduce(String::concat)
.get();
(lambda (bytes &aux (size (* 2 (length bytes))))
(let ((hex (make-array size :element-type 'character :fill-pointer 0)))
(prog1 hex
(with-output-to-string (o hex)
(map () (lambda (byte) (format o "~2,'0x" byte)) bytes)))))
Compute resulting hex string size, write to it as a string with format function
fn byte_to_hex(byte: u8) -> (u8, u8) {
static HEX_LUT: [u8; 16] = [b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9', b'a', b'b', b'c', b'd', b'e', b'f'];
let upper = HEX_LUT[(byte >> 4) as usize];
let lower = HEX_LUT[(byte & 0xF) as usize];
(lower, upper)
}
let utf8_bytes: Vec<u8> = a.iter().copied().flat_map(|byte| {
let (lower, upper) = byte_to_hex(byte);
[upper, lower]
}).collect();
let s = unsafe { String::from_utf8_unchecked(utf8_bytes) };