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 code | Description |
|---|---|
| 90811 | An unsupported character set was specified. |
Usage examples
-
Converting a string to UTF-8 binary
json "{'val': 'hello'}" | eval result = binary(val) | # result: 68656c6c6f -
Converting with an explicitly specified character set
json "{'val': 'hello'}" | eval result = binary(val, "us-ascii") | # result: 68656c6c6f -
Verifying binary as a hexadecimal string
json "{'val': 'hello'}" | eval result = tohex(binary(val)) | # result: "68656c6c6f" -
NULL input
json "{'val': null}" | eval result = binary(val) | # result: null
Compatibility
The binary() function has been available since before Sonar 4.0.