Sign in Join
Wiki copytemporary

Byte: what changed

Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.

Title: Byte

OldNewLine
1+A `byte` is an unsigned [[Integer|integer]] in the range of `0..255`. A `byte` is 8 bits long. A `byte` and a [[Char|char]] are virtually the same thing as of version 3 of [[FPC]].
2+
3+## Valid values
4+
5+The key difference is, a `byte` can only be referred to as a numeric [[Type|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|ansiChar]], but in the future `char` may be considered a synonym for [[WideChar|wideChar]], not `ansiChar`.
6+
7+For example:
8+
9+``` pascal
10+program byteDemo(input, output, stderr);
11+
12+var
13+ foo: byte;
14+ bar: char;
15+
16+begin
17+ // those two assignments are physically the same
18+ foo := 65;
19+ bar := 'A';
20+
21+ // although they are the same action,
22+ // the following would be illegal
23+ //foo := 'A';
24+ //bar := 65;
25+end.
26+```
27+
28+The use of `byte` or `byte` as a data type provides better documentation as to the purpose of the use of the particular variable.
29+
30+## Standard functions
31+
32+### Conversion to and from character
33+
34+The `byte` type can be [[coersion|coerced]] to `char` by using the [[Chr|chr function]]. Char type values can be coerced to byte by using the [[Ord|ord function]].
35+
36+The above program corrected to legal use:
37+
38+``` pascal
39+program ordChrDemo(input, output, stderr);
40+
41+var
42+ foo: byte;
43+ bar: char;
44+
45+begin
46+ foo := 65;
47+ bar := 'A';
48+
49+ foo := ord('A');
50+ // chr(65) is equivalent to #65
51+ bar := chr(65);
52+ bar := #65;
53+
54+ // alternatively: typecasts
55+ // typecasts of constant expressions
56+ // are guaranteed to happen at compile-time
57+ foo := byte('A');
58+ bar := char(65);
59+end.
60+```
61+
62+### String representation
63+
64+The [`binStr` function](https://www.freepascal.org/docs-html/rtl/system/binstr.html) from the [[System unit|system unit]] can be used to get a [[String|string]] showing the [[Binary numeral system|binary representation]] of a `byte`:
65+
66+``` pascal
67+program binStrDemo(input, output, stderr);
68+
69+var
70+ foo: byte;
71+
72+begin
73+ foo := 10;
74+ writeLn(binStr(foo, 8));
75+end.
76+```
77+
78+The output is:
79+
80+```text
81+00001010
82+```
83+
84+A more versatile function is [`intToBin` provided by the `strUtils` unit](https://www.freepascal.org/docs-html/rtl/strutils/inttobin.html).
85+
86+---
87+*From the Free Pascal wiki, page "Byte", as it stood on 2022-05-26 after a change by Trev, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*

Back to history