简体   繁体   English

从字节数组获取位0

[英]Get Bit 0 from Byte array

I have wrapped a C++ API in C#. 我在C#中包装了C ++ API。 This API fills the supplied memory location with a byte array that represents program settings. 此API用表示程序设置的字节数组填充提供的内存位置。 I need to get Bit 0 to determine its state. 我需要获取位0才能确定其状态。 Here is the C++ API and usage documentation: 这是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
);

Here is my C# wrapper and call (what i assume to be correct): 这是我的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);

How do i get bit 0? 我如何获得位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) 尝试GetBit(bytearray[0],7)

You should look at using the BitArray structure to make your life easier. 您应该考虑使用BitArray结构来简化生活。 Create the BitArray from your byte and you can check the bits you need. 从您的字节创建BitArray,然后可以检查所需的位。 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. Windows和大多数Linux发行版都是低端格式 ,因此对于.Net程序而言,这可能是一个安全的选择。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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