Byte

From Free Pascal wiki
Jump to: navigation, search

Deutsch (de) English (en) suomi (fi) français (fr) italiano (it) 中文(中国大陆)‎ (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 the same thing as of version 3 of Free Pascal, except 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:

var 
  c: byte; 
  ch: char;
begin
  c := 65;  ch := 'A';  { are the same action, and are legal }
  c := 'A'; ch := 65;   { while they are the same action, this is illegal }
end.

The use of byte or char as a data type provides better documentation as to the purpose of the use of the particular variable. 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:

var
  c: byte; 
  ch: char;
begin
  c := 65;  ch := 'A'; { are the same action, and are legal }
  c := ord('A');  ch := Chr(65); { now legal ... ch := Chr(65); is equivalent to ch := #65}
  c := Byte('A'); ch := Char(65); { now legal and guaranteed to happen at compile time }
end.

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

uses StrUtils;
 
var
   a_byte : Byte = 10;
 
begin
   Writeln(IntToBin(a_byte,8));
end.

The output is:

00001010

Data Types
Simple Data Types Boolean | Byte | Cardinal | Char | Currency | Extended | Int64 | Integer | Longint | Pointer | Real | Shortint | Smallint | Word
Complex Data Types Array | Class | Record | Set | String | ShortString