Trying the convert an Integer to a Packed Record of 32 booleans.
Please note that SizeOf(Integer) = 4
while SizeOf(<packed record of 32 booleans>) = 32
because SizeOf(Boolean) = 1
(1 byte = 8 bits). You seem to be under the impression that a Boolean
is a single bit; it isn't.
If that had been the case, however, you could simply have cast the integer to such a record.
(But of course it is trivially possible to write a function that "converts" an integer to a record of 32 booleans.)
The standard approach to use the bits in an integer is to use bitwise operators:
const
HasScreen = 1;
HasSound = 2;
HasKeyboard = 4;
HasMouse = 8;
HasInternet = 16;
var
ComputerProperties: Integer;
begin
// Test a bit
if ComputerProperties and HasInternet = 0 then
ShowMessage('You need an Internet connection.');
// Set a bit
Computer := Computer or HasInternet;
// Clear a bit
Computer := Computer and not HasInternet;
In Delphi, it is more idiomatic to use sets:
type
TComputerFeature = (cfScreen, cfSound, cfKeyboard, cfMouse, cfInternet);
TComputerFeatures = set of TComputerFeature;
var
Features: TComputerFeatures;
begin
Features := [cfScreen, cfKeyboard];
if not (cfInternet in Features) then
ShowMessage('You need an Internet connection.');
Include(Features, cfInternet);
Exclude(Features, cfInternet);
end;
You may, however, easily simulate your original design approach using advanced records:
type
TBit32 = type Integer;
TBit32Helper = record helper for TBit32
strict private
function GetBit(Index: Integer): Boolean;
procedure SetBit(Index: Integer; const Value: Boolean);
public
property Bit[Index: Integer]: Boolean read GetBit write SetBit;
end;
function TBit32Helper.GetBit(Index: Integer): Boolean;
begin
Result := (Self shr Index) and 1 <> 0;
end;
procedure TBit32Helper.SetBit(Index: Integer; const Value: Boolean);
begin
if Value then
Self := Self or (1 shl Index)
else
Self := Self and not (1 shl Index);
end;
begin
var x: Integer := 123;
Writeln(TBit32(x).Bit[4]); // read
TBit32(x).Bit[6] := False; // write