Word to byte

Hi,

How to convert Word into array of bytes?
Who is Participating?

x

Senior DeveloperCommented:
just use Lo() and Hi()
eg.

var
w: word;
i: integer;
results: array[0..1] of byte;
begin
w := 12345;
results[0] := lo(w);
results[1] := hi(w);
for i := Low(results) to high(results) do
0

You can also move the data, or just perform a simple cast of the word data.

Russell

-----------

eg:

var  w:       word;
i:       integer;
results: Array[0..1] of byte;
begin

w:=12345;

// Split high and low bytes
results[0] := lo(w);
results[1] := hi(w);
for i := Low(results) to high(results) do

// Move data
Move(w, results, SizeOf(Word));
for i := Low(results) to high(results) do

// Cast data
for i:=0 to 1 do

end;
0

Commented:
Another option is this:

type

TWordBytes = record
byte1, byte2: byte;
end;

...
var ba: TWordBytes;
w: word;
begin
w:= 1000;
ba:= TWordBytes(w);
ShowMessage(IntToStr(ba.byte1)+', '+IntToStr(ba.byte2));
0

Commented:
0

Self-employed developerCommented:
Or, the most interesting solution:

program Project3;
{\$APPTYPE CONSOLE}
var
W: Word;
B: array[0..1] of byte absolute W;
begin
W := \$1234;
WriteLn(B[0]);
WriteLn(B[1]);
end.

Keep in mind that words are stored with the low-byte first. Thus B[0] is the low byte and B[1] is the high byte. The absolute directive just tells Delphi that B is located at exactly the same address as W. Thus, no need to assign one to another or do some typecasting...

The use of Lo() and Hi() -as suggested by others- does tend to be a bit more reliable though, since your Pascal code might one day be compiled for a processor that doesn't do Little-Ednian storage of data. (Intel uses Little-Endian, meaning that in memory, the low byte comes before the high byte.)
0

Commented:
note: sorry, but the points (5) were not enough to split between all 4 of you so I went with the first 2 solutions.
0

Commented:
Forced accept.

Computer101