2014-02-17 55 views
1

我有一些約束,像這樣:轉換十進制數的標誌值

interesting = 0x1 
choked = 0x2 
remote_interested = 0x4 
remote_choked = 0x8 
supports_extensions = 0x10 
local_connection = 0x20 
handshake = 0x40 
connecting = 0x80 
queued = 0x100 
on_parole = 0x200 
seed = 0x400 
optimistic_unchoke = 0x800 
rc4_encrypted = 0x100000 
plaintext_encrypted = 0x200000 

和文檔告訴我「的標誌屬性會告訴你哪個狀態同行是在它被設置爲任意組合上述」的枚舉所以基本上我調用的DLL,它在結構填充與代表標誌值的十進制數,舉幾個例子:

2086227 
170 
2098227 
106 

如何從小數點確定的標誌嗎?

回答

4

爲了確定設置了哪些標誌,您需要使用bitwise AND操作(Lua 5.2中的bit32.band())。例如:

function hasFlags(int, ...) 
    local all = bit32.bor(...) 
    return bit32.band(int, all) == all 
end 

if hasFlags(2086227, interesting, local_connection) then 
    -- do something that has interesting and local_connection 
end 
+4

在Lua 5.1或LuaJIT中,bit32不可用,但您可以改用luabitop。它來自LuaJIT本地,您需要爲它安裝它。 – catwell

+1

在Lua 5.1中存在'bit32'的後端口(https://raw.github.com/hishamhm/lua-compat-5.2/bitlib-5.2.2/lbitlib.c)。它存在於LuaRocks和LuaDist中。而LuaJIT有它自己的位庫 – moteus