binary()

Converts a string to binary encoded with the specified character set.

Syntax

binary(STR_EXPR[, CHARSET])

The encode() function provides the same functionality.

Parameters

STR_EXPR
The string or expression to convert to binary. If an array is passed, each element is converted individually.
CHARSET
The character set name to use for encoding (default: utf-8). Use the Preferred MIME Name or Aliases registered in IANA Charset. Refer to the IANA Charset Registry for the list of registered character sets.

Description

The binary() function encodes a string using the specified character set and returns it as binary (byte[]). If the argument is null, returns null. If a non-string value is passed, returns null. If an array or list is passed, the conversion is applied recursively to each element.

Specifying an unsupported character set name causes an error during the parsing phase.

Error codes

Error codeDescription
90811An unsupported character set was specified.

Usage examples

  1. Converting a string to UTF-8 binary

    json "{'val': 'hello'}" | eval result = binary(val)
    | # result: 68656c6c6f
    
  2. Converting with an explicitly specified character set

    json "{'val': 'hello'}" | eval result = binary(val, "us-ascii")
    | # result: 68656c6c6f
    
  3. Verifying binary as a hexadecimal string

    json "{'val': 'hello'}" | eval result = tohex(binary(val))
    | # result: "68656c6c6f"
    
  4. NULL input

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

Compatibility

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