C#byte数组获取每一位值

获取byte中每一位的值

byte byData = 0x36;

int n0, n1, n2, n3, n4, n5, n6, n7;
n0 = (byData & 0x01) == 0x01 ? 1 : 0;
n1 = (byData & 0x02) == 0x02 ? 1 : 0;
n2 = (byData & 0x04) == 0x04 ? 1 : 0;
n3 = (byData & 0x08) == 0x08 ? 1 : 0;
n4 = (byData & 0x10) == 0x10 ? 1 : 0;
n5 = (byData & 0x20) == 0x20 ? 1 : 0;
n6 = (byData & 0x40) == 0x40 ? 1 : 0;
n7 = (byData & 0x80) == 0x80 ? 1 : 0;

获取int16中其中某几位的数值

bit 内容  
11-15 预留  
10 值7  
6-9 值6  
5 值5  
4 值4  
3 值3  
2 值2  
0-1 值1  

/// <param name="val"></param> public virtual void SetValue(UInt16 val) { Fac = (Enmus.FactoryDebugStatus)(val & 0x03); Fligh = (Enmus.FlyLock)((val & 0x04)); Remoti = (Enmus.RemotingLock)(val & 0x08); Air = (Enmus.AirCtrl)((val & 0x10)); Alt = (Enmus.AltHold)((val & 0x20)); Vertl = (Enmus.VerticalCtrl)(((val >> 6) & 0x0F)); Engin= (Enmus.Start_StopState)((val & 0x400)); }

 结构体和byte数组互相转换

        /// <summary>
        /// 结构体转byte数组
        /// </summary>
        /// <param name="structObj"></param>
        /// <returns></returns>
        public static byte[] StructToBytes<T>(T structObj) where T : struct
        {
            //得到结构体的大小
            int size = Marshal.SizeOf(structObj);
            //创建byte数组
            byte[] bytes = new byte[size];
            //分配结构体大小的内存空间
            IntPtr structPtr = Marshal.AllocHGlobal(size);
            //将结构体拷到分配好的内存空间
            Marshal.StructureToPtr(structObj, structPtr, false);
            //从内存空间拷到byte数组
            Marshal.Copy(structPtr, bytes, 0, size);
            //释放内存空间
            Marshal.FreeHGlobal(structPtr);
            //返回byte数组
            return bytes;
        }

        /// <summary>
        /// byte数组转结构体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static T BytesToStuct<T>(byte[] bytes) where T : struct
        { 
            //得到结构体的大小
            Type type = typeof(T);
            int size = Marshal.SizeOf(type);
            //byte数组长度小于结构体的大小
            if (size > bytes.Length)
            {
                //返回空
                return default(T);
            }
            //分配结构体大小的内存空间
            IntPtr structPtr = Marshal.AllocHGlobal(size);
            //将byte数组拷到分配好的内存空间
            Marshal.Copy(bytes, 0, structPtr, size);
            //将内存空间转换为目标结构体
            var obj = Marshal.PtrToStructure(structPtr, type);
            //释放内存空间
            Marshal.FreeHGlobal(structPtr);
            if (obj is T t)
            {
                return t;
            }
            return default(T);
        }

 

 

热门相关:恭喜你被逮捕了   后福   拒嫁豪门,前妻太抢手   后福   豪门情变,渣总裁滚远点!