简体   繁体   中英

Get Bit 0 from Byte array

I have wrapped a C++ API in C#. This API fills the supplied memory location with a byte array that represents program settings. I need to get Bit 0 to determine its state. Here is the C++ API and usage documentation:

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
);

Here is my C# wrapper and call (what i assume to be correct):

        [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);

How do i get bit 0?

I've tried (with no success):

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

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

Are you looking for the most significant bit or the least significant bit?

Usually first refers to the most significant bit within a Byte and you are getting the least significant bit.

Try GetBit(bytearray[0],7)

You should look at using the BitArray structure to make your life easier. Create the BitArray from your byte and you can check the bits you need. Remember what Guvante pointed out though - the bits may be stored from least significant to most significant. Windows and most Linux distros are little endian , so that's probably a safe bet to make for a .Net program.

我所有的代码都是正确的... API供应商为我提供了不正确的ID参数(第三个值)...我很感谢所有注释以及我对Guvante解释的从最低到最高有效位的新理解。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM