User Tools

Site Tools


string_char_byte

String, Char and Byte

In .NET every string is Unicode.

That means that a string of 10 characters has not more 10 bytes like in VO, but normally has 20 (2 byte per character). And the second, not less important issue: when converting between binary data and strings you need to care about charsets.

You cannot more read a binary file from disk or from the network and keep it in a string!

That was possible in VO or other Win32 languages, but it is not more correct in .NET. In .NET, if reading binary data, you need to use variables defined as byte[], that means .NET array of bytes:

local aBitmap as byte[]
 
aBitmap := File.ReadAllBytes( "c:\data\MyImage.png" )

If you are reading text data, you can read it into a string:

local cBuffer as string
 
cBuffer := File.ReadAllText( "c:\data\MyText.txt", Encoding.ASCII )

Of course, you can convert for and back between strings and character arrays, but you need to specify the Encoding. In some functions, you can also omit it, but then the .NET framework will use the system defined values, and this can lead to unexpected results.

To convert byte arrays to string, there are conversion functions. Please look at the Encoding class in the System.Text namespace in the .NET framework documentation.

local aBytes as byte[]
local cString as string
 
System.Text.Encoding.Unicode.GetString( aBytes )

The inverse process is also possible:

local aBytes as byte[]
local cString as string
 
aBytes := System.Text.Encoding.Unicode:GetBytes( cString )

An array of char values can also be used instead of a string.

To build a string from a char array is very simple, you can use the constructor of the string class:

local aChars as char[]
local cString as string
 
cString := String{ aChars }

For the inverse operation (from a string to a char array) you can use a method of the string class:

local cString as string
local aChars as char[]
 
aChars := cString:ToCharArray()

If you need to initialize a byte array (as every array), you need to write as follows:

local aBuffer as byte[]
 
aBuffer := Byte[]{ 128 }
string_char_byte.txt · Last modified: 2018/08/20 04:04 by wolfgangriedmann