2009-11-11 43 views
0

難道有人請幫助我關於浮點變量的字節順序嗎?實際上,代碼在Solaris上正常工作,但不在Windows Xp上。這裏是我的代碼一塊例如: ....如何將浮點數轉換爲無符號變量?

int x_snd=1; 
float y_snd=1.13; 
struct { 
     int xx_snd; 
     float yy_snd; 
    } data_snd; 
int x_rec; 
float y_rec; 
    struct { 
     int xx_rec; 
     float yy_rec; 
    } data_rec; 

//marshalling 
data_snd.xx_snd=htons(x_snd); 
data_snd.yy_snd=htonl(*(int*) &y_snd); 

//write data to socket 
send(sock1, &data_snd, ... 

//clean ... 

//read data from socket 
if recv(sock, &data_rec ... 

    //unmarshalling 
    x_rec=ntohs(data_rec.xx_rec); 
    y_rec= *(float*) &(ntohl(data_rec.yy_rec)); 

...

釷代碼是用gcc上的Wndows編譯在Unix和與MSVC++ 6。 您的幫助將是非常讚賞,我會很高興,如果你能指點我,讓字節排列順序有用信息的任何鏈接或文件...

請多關照您的幫助, MK

回答

2

還有很多更多的潛力品種和問題浮點格式不僅僅是你必須處理打包和解包整數當與端問題。

一種方法是將浮點數編碼爲文本,使用printf,然後用strtof()(如bmargulies所示)讀回它們。

的另一種方式,只要機器共享相同的FLT_RADIX值,將工作,是將它們分解成尾數和指數值:

#include <math.h> 
#include <limits.h> 

float x = 1.13; 
int x_exp; 
long x_mant; 

x_exp = ilogbf(x); 
x_mant = (scalbnf(fabsf(x), -x_exp) - 1) * LONG_MAX; 
if (x < 0.0) 
    x_mant = -x_mant; 

然後,您有一個intlongx_expx_mant從上面的代碼)放到電線上,您可以使用正常的ntohl()htonl()功能來完成。爲了將這些回一個float,使用:

x = scalbnf((fabsf(x_mant)/LONG_MAX) + 1, x_exp); 
if (x_mant < 0) 
    x = -x; 

注意,大多數機器具有2 FLT_RADIX值(float.h定義),所以如果你在編譯期間檢查該和終止,如果是別的東西,你應該是合理的便攜式。

+0

感謝您的幫助 您能給我說說第二個更多資料你描述?任何描述這種FLT_RADIX值的鏈接都將非常感謝!再次 感謝, MK – make 2009-11-12 01:10:46

+0

嗯,我給你提供的代碼(我只寫我自己,所以我沒有任何鏈接指向你)。如果您對Sign-Mantissa-Exponent表示浮點數的方式進行了一些研究,應該清楚代碼的作用。 – caf 2009-11-12 01:19:05

+0

感謝您的幫助。 請糾正我,如果這是正確的! int x_snd = 1; float y_snd = 1.13; // int y_snd_exp; long y_snd_mant; struct { \t int xx_snd; \t float yy_snd; data_snd; // marshalling y_snd_exp = ilogbf(y_snd); y_snd_mant =(scalbnf(fabsf(y_snd),-y_snd_exp) - 1)* LONG_MAX; if(y_snd <0.0)y_snd_mant = -y_snd_mant; 012_sl.xx_snd = htons(x_snd); data_snd.yy_snd = htonl(y_snd_mant); data_snd.yy_snd = htonl(y_snd_mant); //將數據寫入到插座 發送(sock1,&data_snd,... ... – make 2009-11-12 02:22:13

2

這是一個普遍不好的主意。即使在考慮字節順序之後,浮點數的格式在不同硬件上也不一定相同。我不得不建議將它們作爲字符串在這裏和那裏運送。

1

假設兩個系統具有相同的浮點格式,yy_recfloat; ntohl需要unsigned long;浮點值(可能具有不正確的字節順序)將在傳遞到ntohl時轉換爲整數表示形式。

你應該得到一個編譯器警告,由於從floatunsigned long轉換。

+0

這是至關重要的。作爲編寫的代碼(y_rec = *(*浮動)(再用ntohl(data_rec.yy_rec)); )不應該永遠工作,因爲它會yy_rec(浮點數)轉換爲一個unsigned long,然後翻轉它字節。 – bmargulies 2009-11-12 00:37:30