Byte Arguments and Strings

There is a close association between a string and a byte array—a string is simply an array of bytes that is treated as a series of ASCII characters. Therefore, it is convenient to be able to convert between them easily.

When STRING is called with a single argument of byte type and the FORMAT keyword is not used, STRING does not work in its normal fashion. Instead of formatting the byte data and placing it into a string, it returns a string containing the byte values from the original argument. Thus, the result has one less dimension than the original argument. A two-dimensional byte array becomes a vector of strings, and a byte vector becomes a scalar string. However, a byte scalar also becomes a string scalar. For example, the statement

PRINT, STRING([72B, 101B, 108B, 108B, 111B]) 

produces the output below:

Hello 

This output results because the argument to STRING, as produced by the array concatenation operator, is a byte vector. Its first element is 72B which is the ASCII code for "H," the second is 101B which is an ASCII "e," and so forth. The PRINT keyword can be used to disable this feature and cause STRING to treat byte data in the usual way.

As discussed in Files and Input/Output, it is easier to read fixed-length string data from binary files into byte variables instead of string variables. Therefore, it is convenient to read the data into a byte array and use this special behavior of STRING to convert the data into string form.

Another use for this feature is to build strings that contain nonprintable characters in a way such that the character is not entered directly. This results in programs that are easier to read and that also avoid file transfer difficulties (some forms of file transfer have problems transferring nonprintable characters). Due to the way in which strings are implemented in IDL, applying the STRING function to a byte array containing a null (zero) value will result in the resulting string being truncated at that position. Thus, the statement,

PRINT, STRING([65B, 66B, 0B, 67B]) 

produces the following output:

AB 

This output is produced because the null byte in the third position of the byte array argument terminates the string and hides the last character.

Note
The BYTE function, when called with a single argument of type string, performs the inverse operation to that described above, resulting in a byte array containing the same byte values as its string argument. For additional information about the BYTE function, see Type Conversion Functions.