簡體   English   中英

從字節數組獲取位0

[英]Get Bit 0 from Byte array

我在C#中包裝了C ++ API。 此API用表示程序設置的字節數組填充提供的內存位置。 我需要獲取位0才能確定其狀態。 這是C ++ API和用法文檔:

DECL_FOOAPIDLL DWORD WINAPI FOO_GetVal(
VOID *Val,  //pointer to memory where the data will be stored by the function
DWORD Len,  //length of Val in bytes
DWORD Id    //identification number of the parameter
);

這是我的C#包裝和調用(我認為是正確的):

        [DllImport(FOO_API, CharSet = CharSet.Auto)]
static public extern uint FOO_GetVal(IntPtr val, uint len, uint id);


        IntPtr Ptr = Marshal.AllocHGlobal(5);
        uint hr = NativeWrapper.FOO_GetVal(Ptr, 5, 1181);

        var byteArray = new byte[5];
        Marshal.Copy(Ptr, byteArray, 0, 5);


        Marshal.FreeHGlobal(Ptr);

我如何獲得位0?

我嘗試過(沒有成功):

bool b = GetBit(bytearray[0],0);

private bool GetBit(byte b, int bitnum)
{
    return (b & (1 << nitnum)) != 0;
}

您在尋找最高有效位還是最低有效位?

通常首先是指一個字節中的最高有效位,而您得到的是最低有效位。

嘗試GetBit(bytearray[0],7)

您應該考慮使用BitArray結構來簡化生活。 從您的字節創建BitArray,然后可以檢查所需的位。 請記住古凡特指出的內容-比特可以從最低有效到最高有效存儲。 Windows和大多數Linux發行版都是低端格式 ,因此對於.Net程序而言,這可能是一個安全的選擇。

我所有的代碼都是正確的... API供應商為我提供了不正確的ID參數(第三個值)...我很感謝所有注釋以及我對Guvante解釋的從最低到最高有效位的新理解。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM