2013-02-23 76 views
3

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

感谢您的回答。

回答

-1

你可以做这样的事情:

byte array[4]; 
int source; 

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

然后,如果你胶水数组[1]数组[4]一起,你会得到你的源整数;

编辑:更正了面具。

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

+0

不知道这个C代码是否是Pascal ...也许'#define BEGIN {'? – 2013-02-23 09:14:52

+0

嗯,我很久没有使用帕斯卡了,但不难理解这段代码并将其翻译回来;) – Losiowaty 2013-02-23 09:18:59

+0

对于双F,我已经纠正它。这可能更容易你的方式(如果你可以发表一个例子),但这是首先想到的。 – Losiowaty 2013-02-23 09:23:46

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:我没有帕斯卡尔编码几个月现在这样有可能是错误,随时修复。

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”等。

1

下面是使用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.