如何将整数转换为字节数组?

时间:2013-02-23 09:00:51

标签: pascal

我在ST代码中有一些动作监听器(类似于Pascal),它返回一个整数。然后我有一个CANopen函数,它允许我只以字节数组发送数据。我怎样才能从这些类型转换?

感谢您的回答。

4 个答案:

答案 0 :(得分:3)

您可以使用Move标准函数将整数块复制为四个字节的数组:

var
    MyInteger: Integer;
    MyArray: array [0..3] of Byte;
begin
    // Move the integer into the array
    Move(MyInteger, MyArray, 4);

    // This may be subject to endianness, use SwapEndian (and related) as needed

    // To get the integer back from the array
    Move(MyArray, MyInteger, 4);
end;
PS:我现在几个月没有用Pascal编码,所以可能会有错误,随时修复。

答案 1 :(得分:2)

以下是使用Free Pascal的解决方案。

首先,用“绝对”:

var x: longint;
    a: array[1..4] of byte absolute x;

begin
x := 12345678;
writeln(a[1], ' ', a[2], ' ', a[3], ' ', a[4])
end.

使用指针:

type tarray = array[1..4] of byte;
     parray = ^tarray;

var x: longint;
    p: parray;

begin
x := 12345678;
p := parray(@x);
writeln(p^[1], ' ', p^[2], ' ', p^[3], ' ', p^[4])
end.

使用二元运算符:

var x: longint;

begin
x := 12345678;
writeln(x and $ff, ' ', (x shr 8) and $ff, ' ',
        (x shr 16) and $ff, ' ', (x shr 24) and $ff)
end.

记录:

type rec = record
              case kind: boolean of
              true: (int: longint);
              false: (arr: array[1..4] of byte)
           end;

var x: rec;

begin
x.int := 12345678;
writeln(x.arr[1], ' ', x.arr[2], ' ', x.arr[3], ' ', x.arr[4])
end.

答案 2 :(得分:1)

您还可以使用变量记录,这是在不使用指针的情况下故意在Pascal中对变量进行别名的传统方法。

type Tselect = (selectBytes, selectInt);
type bytesInt = record
                 case Tselect of
                   selectBytes: (B : array[0..3] of byte);
                   selectInt:   (I : word);
                 end; {record}

var myBytesInt : bytesInt;

变量记录的好处在于,一旦设置完毕,您就可以自由地以任一形式访问变量,而无需调用任何转换例程。例如,“ myBytesInt.I:= $ 1234 ”,如果您想以整数形式访问它,或“ myBytesInt.B [0]:= 4 ”等,如果您想要您可以将其作为字节数组访问。

答案 3 :(得分:-1)

您可以这样做:

byte array[4];
int source;

array[0] = source & 0xFF000000;
array[1] = source & 0x00FF0000;
array[2] = source & 0x0000FF00;
array[3] = source & 0x000000FF;

然后,如果将数组[1]粘合到数组[4],您将获得源整数;

编辑:更正了面具。

编辑:正如托马斯在评论中指出的那样 - >你仍然需要将ANDing的结果值移位到LSB以获得正确的值。