Could we have a reality check please: I think you're actually talking about /packing/, not /viewing/.
Sorry about using the wrong verb. I meant to do this:
R M L
┄┄┄┄┄┄┌───┬───┬───┐
7 │ 6 │ 5 │ 4 │ 3 │ Dn
┄┄┄┄┄┄├───┼───┼───┤
│ 2 │ 1 │ 0 │ Up
└───┴───┴───┘
For me, the bits are already (bit)packed, but I want to “believe”, think (“view”) they were arranged in a matrix.
[…] This can be done with casting. […]
Thanks for your suggestion, but I’d like to avoid casting if I had to it every time I access the bit matrix.
function TForm1.v(x,y : byte) : boolean;
begin
result := num and (1 shl (y*3 + x)) > 0;
end;
which comes close to allowing something like v[x,y] being v(x,y).
Wow, that’s concise. Any idea how I could avoid having to specify the function name? I mean, properties (in the context of type helpers), but then still I had specify the property name.
In reminiscence of the ole
pack and
unpack I think I’m actually gonna define and utilize
implicit operator overloads:
{$mode objFPC}
program bitpackedArray(input, output, stdErr);
type
xAxis = (left, middle, right);
yAxis = (up, down);
z = type Byte; // this may not be an array data type
zUnpacked = array[xAxis, yAxis] of Boolean;
// otherwise these operator overloads will horribly go wrong
{$optimization regVar+}
operator := (const bits: z): zUnpacked;
var
v: bitpacked array[1..6] of Boolean absolute bits;
begin
result[left, up] := v[1];
result[middle, up] := v[2];
result[right, up] := v[3];
result[left, down] := v[4];
result[middle, down] := v[5];
result[right, down] := v[6];
end;
operator := (const unpacked: zUnpacked): z;
var
v: bitpacked array[1..6] of Boolean absolute result;
begin
v[1] := unpacked[left, up];
v[2] := unpacked[middle, up];
v[3] := unpacked[right, up];
v[4] := unpacked[left, down];
v[5] := unpacked[middle, down];
v[6] := unpacked[right, down];
end;
function foobar(const given: z): zUnpacked;
begin
foobar := given; // implicit operator z → unpacked
foobar[left, up] := true;
end;
var
data: z;
begin
data := default(z);
data := foobar(data); // implicit operator unpacked → z
writeLn(data);
end.
It’s of course a trade-off between fast and convenient access versus introducing unnecessary overhead. Alas, using the RTL’s
pack/
unpack wouldn’t work, because the arrays would have to have same dimension specifications and since the
bitpacked array has the wrong size, I have to do it manually as show above.