mirror of
https://github.com/status-im/nim-stew.git
synced 2025-02-13 12:36:57 +00:00
add to0xHex
which returns a 0x
-prefixed hex string
This commit is contained in:
parent
4750020a44
commit
17cd8c846f
@ -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
|
||||
|
@ -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 ==
|
||||
|
Loading…
x
Reference in New Issue
Block a user