2013-02-23 45 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.