add `to0xHex` which returns a `0x`-prefixed hex string

This commit is contained in:
Jacek Sieka 2022-01-06 17:05:47 +01:00
parent 4750020a44
commit 17cd8c846f
No known key found for this signature in database
GPG Key ID: A1B09461ABB656B8
2 changed files with 24 additions and 8 deletions

View File

@ -115,29 +115,44 @@ func hexToSeqByte*(hexStr: string): seq[byte]
for i in 0 ..< N:
result[i] = hexStr[2*i + skip].readHexChar shl 4 or hexStr[2*i + 1 + skip].readHexChar
func toHexAux(ba: openArray[byte]): string =
func toHexAux(ba: openArray[byte], with0x: static bool): string =
## Convert a byte-array to its hex representation
## Output is in lowercase
## No "endianness" reordering is done.
const hexChars = "0123456789abcdef"
let sz = ba.len
result = newString(2 * sz)
for i in 0 ..< sz:
result[2*i] = hexChars[int ba[i] shr 4 and 0xF]
result[2*i+1] = hexChars[int ba[i] and 0xF]
let extra = when with0x: 2 else: 0
result = newStringOfCap(2 * ba.len + extra)
when with0x:
result.add("0x")
for b in ba:
result.add(hexChars[int(b shr 4 and 0x0f'u8)])
result.add(hexChars[int(b and 0x0f'u8)])
func toHex*(ba: openArray[byte]): string {.inline.} =
## Convert a byte-array to its hex representation
## Output is in lowercase
## No "endianness" reordering is done.
toHexAux(ba)
toHexAux(ba, false)
func toHex*[N: static[int]](ba: array[N, byte]): string {.inline.} =
## Convert a big endian byte-array to its hex representation
## Output is in lowercase
## No "endianness" reordering is done.
toHexAux(ba)
toHexAux(ba, false)
func to0xHex*(ba: openArray[byte]): string {.inline.} =
## Convert a byte-array to its hex representation
## Output is in lowercase
## No "endianness" reordering is done.
toHexAux(ba, true)
func to0xHex*[N: static[int]](ba: array[N, byte]): string {.inline.} =
## Convert a big endian byte-array to its hex representation
## Output is in lowercase
## No "endianness" reordering is done.
toHexAux(ba, true)
func toBytes*(s: string): seq[byte] =
## Convert a string to the corresponding byte sequence - since strings in

View File

@ -57,6 +57,7 @@ suite "Byte utils":
expect(ValueError): discard hexToSeqByte("1234567")
expect(ValueError): discard hexToSeqByte("X")
expect(ValueError): discard hexToSeqByte("0")
check simpleBArray.to0xHex == "0x12345678"
test "Array concatenation":
check simpleBArray & simpleBArray ==