Byte

From Lazarus wiki
Jump to: navigation, search

Deutsch (de) English (en) suomi (fi) français (fr) italiano (it) русский (ru) 中文(中国大陆)‎ (zh_CN)

A byte is an unsigned integer in the range of 0..255. A byte is 8 bits long. A byte and a char are virtually the same thing as of version 3 of FPC.

valid values

The key difference is, a byte can only be referred to as a numeric type, while a char can be used as a character, or as part of a string type, and cannot be used in an arithmetic expression. A byte will always be the same size as an ansiChar, but in the future char may be considered a synonym for wideChar, not ansiChar.

For example:

program byteDemo(input, output, stderr);
 
var 
	foo: byte;
	bar: char;
 
begin
	// those two assignments are physically the same
	foo := 65;
	bar := 'A';
 
	// although they are the same action,
	// the following would be illegal
	//foo := 'A';
	//bar := 65;
end.

The use of byte or byte as a data type provides better documentation as to the purpose of the use of the particular variable.

standard functions

conversion to and from character

The byte type can be coerced to char by using the chr function. Char type values can be coerced to byte by using the ord function.

The above program corrected to legal use:

program ordChrDemo(input, output, stderr);
 
var
	foo: byte;
	bar: char;
 
begin
	foo := 65;
	bar := 'A';
 
	foo := ord('A');
	// chr(65) is equivalent to #65
	bar := chr(65);
	bar := #65;
 
	// alternatively: typecasts
	// typecasts of constant expressions
	// are guaranteed to happen at compile time
	foo := byte('A');
	bar := char(65);
end.

string representation

The binStr function from the system unit can be used to get a string showing the binary representation of a byte:

program binStrDemo(input, output, stderr);
 
var
	foo: byte;
 
begin
	foo := 10;
	writeLn(binStr(foo, 8));
end.

The output is:

00001010

A more versatile function is intToBin provided by the strUtils unit.


navigation bar: data types
simple data types

boolean byte cardinal char currency extended int64 integer longint pointer real shortint smallint word

complex data types

array class object record set string shortstring