2012-10-30 60 views
0

C++雙重價值transfering

unsigned char lbytes[] = { 0x0A, 0x01, 0x02 }; 
unsigned char bytes[10]; 

double dbl = sin((double)i) * 10; 

i+=5; if (i == 360) i = 0; 

memcpy(&bytes, &lbytes, 3); 
cout << dbl << endl; 
memcpy(&bytes[3], &dbl, sizeof(double)); 

C#

switch (m[1]) { 
    case 0x01: { 
     if (m.Length > 5) { 
      double myval = Math.Round(BitConverter.ToDouble(m, 3), 2); 

但事情錯在這裏,設爲myVal是alsways一些非常小的值,並與rount它始終爲0。

問題是:我的錯誤在哪裏,我可以在cout中看到有效值,我發送10個字節,出了什麼問題?

+2

難道你不是在拷貝數組的邊界嗎? –

+1

聽起來像一個排序差異(大端與小端)。 'BitConverter'使用CPU-endianness,所以你可能不得不倒轉塊。我最近發佈了一些答案...試試:http://stackoverflow.com/questions/13044200/converting-float-values-of-big-endian-to-little-c-sharp/13044715#13044715(你'我需要擴大到8個字節的雙倍,顯然) –

+0

這只是我的錯誤發送只有10個字節 – Cynede

回答

1

問題是你發送只有十個字節。雙擊是八個字節,再加上你的三個字節的頭部,這意味着你應該發送11個字節。

如果你調整你的bytes數組併發送正確的長度,它應該工作。