2012-07-24 38 views
0

我想在套接字上發送文件,並且需要在前四個字節中傳遞其長度。在ruby中將整數轉換爲字符串

這是我想在C++做的:

struct 
{ 
    int lenght; //four bytes 
    char msg[40]; 
}dataBuf; 

write(fd, &databuf, sizeof(dataBuf)) 

如何推動一個整數到一個插座,所以它接收它作爲一個整數,在另一端,而不是作爲一個ASCII值?

我不想像「\x04\X03」那樣對其進行硬編碼,我試圖用pack(L*)來完成。這隻適用於數組,我沒有辦法將我的四字節整數分成四個字節的數組。

+0

這是你想要做的嗎? http://stackoverflow.com/questions/941856/write-binary-file-in-ruby – HeatfanJohn 2012-07-24 21:00:36

回答

4

嘗試將整數放入一個數組,然後使用pack。例如:

socket.write([0xffff].pack("L")) 
1

看看BinData寶石。

你舉的例子可能是這樣的:

class DataBuf < BinData::Record 
    uint32 :length 
    array :msg, :initial_length => 40 do 
    uint8 
    end 
end 

io = File.open(...) 
r = DataBuf.read(io) 
puts "Data buffer is #{r.length} length and it has '#{r.msg}' message" 

我不知道有關消息,你應該看看BinData文檔的絃樂部分。