fromhex()

Converts a hexadecimal string to binary and returns it.

Syntax

fromhex(HEX_STR)

Parameters

HEX_STR
A hexadecimal string or expression. Both uppercase and lowercase are accepted (0-9, a-f, A-F).

Description

The fromhex() function converts a hexadecimal string to binary (byte[]) and returns it. Returns null in the following cases:

  • The argument is null
  • The argument is not a string
  • The string length is odd (cannot be split into bytes)
  • The string contains non-hexadecimal characters

Passing a numeric constant or a negative number directly as an argument causes an error during the parsing phase.

Error codes

Error codeDescription
90904A numeric constant or negative constant was passed as an argument.

Usage examples

  1. Converting a hexadecimal string to binary and decoding it as a string

    json "{'val': '68656c6c6f'}" | eval result = decode(fromhex(val))
    | # result: "hello"
    
  2. Converting and verifying as hexadecimal again

    json "{'val': '68656c6c6f'}" | eval result = tohex(fromhex(val))
    | # result: "68656c6c6f"
    
  3. Odd-length string input

    json "{'val': '616263646'}" | eval result = fromhex(val)
    | # result: null
    
  4. NULL input

    json "{'val': null}" | eval result = fromhex(val)
    | # result: null
    

Compatibility

The fromhex() function has been available since before Sonar 4.0.