[英]Converting two bytes to one byte and vice versa
我需要開發兩個函數來對字節進行合並和分離操作。
public byte Combine(Byte a, Byte b)
{
// ... Operations ...
}
public byte[] Separate(Byte input)
{
// ... Operations ...
}
public static void Main(String[] args)
{
Byte a, b, c;
a = <SOME BYTE VALUE>;
b = <SOME OTHER BYTE VALUE>;
Console.Writeline("Before Operation");
Console.Writeline("a = " + Convert.ToString(a, 2));
Console.Writeline("b = " + Convert.ToString(b, 2));
// Combine Function called...
c = Combine(a, b);
// Separate Function called...
byte[] d = Separate(c);
a = d[0];
b = d[1];
Console.Writeline("After Operation");
Console.Writeline("a = " + Convert.ToString(a, 2));
Console.Writeline("b = " + Convert.ToString(b, 2));
Console.ReadKey();
}
我已經嘗試了很多方法,例如執行AND,OR,XOR,NAND,NOT和LEFT的組合以及對此進行的RIGHT SHIFT操作,以實現上述功能。
我只是想知道有沒有辦法做到這一點,或者Wether首先可以編寫這種類型的函數。
請您提出寶貴的建議和意見...
就像您在注釋中看到的那樣,您不能在1個字節內存儲2個字節。 如果可以實現,那么您可能是世界上最聰明的人-每個數據都可以壓縮兩次!
相反,您可以在32位int中存儲兩個16位int:
public static uint ToInt(ushort first, ushort second)
{
return (uint)(first << 16) | second;
}
public static ushort ExtractFirst(uint val)
{
return (ushort)((val >> 16) & ushort.MaxValue);
}
public static ushort ExtractSecond(uint val)
{
return (ushort)(val & ushort.MaxValue);
}
接下來,我們可以將兩個字節存儲為一個16位int
:
public static ushort ToShort(byte first, byte second)
{
return (ushort)((first << 8) | second);
}
public static byte ExtractFirst(ushort location)
{
return (byte)((location >> 8) & byte.MaxValue);
}
public static byte ExtractSecond(ushort location)
{
return (byte)(location & byte.MaxValue);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.