0

I have an integer with length 8, an example could be 12345678. I need to turn this into an array of bytes such as xx yy zz gg

how do i go about converting this in pascal?

1

1 Answer 1

0

In modern pascal, you can just cast the value, using parentheses.

For example, in free pascal:

{$mode fpc}
program bytecast;
uses sysutils;
  type bytes = array[0..3] of byte;
  var x : uint32 = $12345678; i : byte; b : bytes;
begin
  b := bytes(x);
  for i := 0 to 3 do Writeln('$',IntToHex(b[i],1))
end.

output:

$78
$56
$34
$12

Note that the "backwards" order here comes from the fact that I'm running on an x86 architecture, which uses a little-endian byte order.

If cross-platform portability is a concern, then you can either extract the bytes manually:

{ var r : uint32; ... }
for i := 0 to 3 do                                                          
  begin
    DivMod(x, $100, x, r); { needs 'uses math'. note: this destroys x! }
    b[3-i] := r
  end;

Now the bytes will be arranged in a more intuitive order, and the output of the earlier WriteLn loop becomes:

$12
$34
$56
$78

This will work on all platforms as well as any pascal dialect that prevents simple casting, at the cost of doing a little more work. (For another option, see the SwapEndian procedure and this FPC wiki page about cross platform code.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.