From m204wiki
Jump to navigation Jump to search

Convert binary byte string to integer

Note: Many $functions have been deprecated in favor of Object Oriented methods. The OO equivalent for the $C2D function is the BinaryToInteger function. For a full list of string and numeric conversion functions see List of String methods and List of Float methods.

The $C2D function returns the integer which is represented by a binary byte string argument.

$C2D accepts one required and one optional argument and returns a numeric value.

The first argument is the binary byte string to be converted to an integer. If it is omitted or is the null string, zero is the result.

The second argument is the number of bytes to use from argument one. If this is longer than argument one, argument one is padded with leading zeroes to this length; otherwise the rightmost bytes of argument one are used. The default is 5.

The returned result is the integer represented, in binary, by the byte string value of argument one. This is obtained from the rightmost bytes of the first argument, after any padding or truncating to the length specified by argument 2. If the length of argument one is 4 or more, or if argument two is less than or equal to the length of argument one, these bytes are treated as a signed number; otherwise they are treated as an unsigned number. A zero is returned for invalid arguments.


%value = $C2D(byte_string, [width])

%value is set to the integer represented by the byte string.

Usage notes

$C2D is similar to the standard $Unbin function, with some differences, such as being able to specify the input length in bytes rather than bits, and being able to specify input lengths other than 2 or 4 bytes in length.

The inverse of $C2D is $D2C. See also the $D2X and $X2D functions, and see the $C2X and $X2C functions.


The following program will print the value -1:

B PRINT $C2D($X2C('FF'), 1) END

Here are some other results, with the input shown using hexadecimal representation, or as ' ' to indicate the null string:

$C2D(X'09') -> 9 $C2D(X'81') -> 129 $C2D(X'FF81') -> 65409 $C2D('') -> 0 $C2D(X'81') -> 129 $C2D(X'81', 1) -> -127 $C2D(X'81', 2) -> 129 $C2D(X'FF81', 2) -> -127 $C2D(X'FF81', 1) -> -127 $C2D(X'FF7F', 1) -> 127 $C2D(X'F081', 2) -> -3967 $C2D(X'F081', 1) -> -127 $C2D(X'0031', 0) -> 0 $C2D(X'FFFFFFFF') -> -1 $C2D(X'FFFFFF') -> 16777215

Products authorizing $C2D

Products authorizing $C2D