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

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章