2014-10-06 212 views
0

我需要开发两个函数来对字节进行组合和分离操作。将两个字节转换为一个字节,反之亦然

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,NOTLEFT以及这个右SHIFT操作来实现上述功能很多东西。

我只想知道是否有任何方法可以做到这一点,或者Wether写这种类型的函数是完全可能的。

请给我宝贵的建议和意见...

+0

这是不可能的。请参阅鸽子的原理。 – user1937198 2014-10-06 11:21:13

+0

没有可能将两个字节存储为一个字节,以允许重现输入。我看到在Int32中存储两个'Int16'数字的唯一方法 - 它可以通过一个小的kownledge来完成,如何存储32位int并移位操作。 – 2014-10-06 11:21:25

+0

您正在将一组较大的值(2个字节)转换为较小的一组(1个字节)。您肯定会碰到冲突,因此无法可靠地将1个字节映射回原来的2个字节。 – juharr 2014-10-06 11:21:39

回答

1

就像你可以在评论中看到的,你不能在1字节内存储2个字节。如果能够实现它,你可能会成为世界上最有天赋的人 - 每一个数据都可以被压缩两次!

相反,你可以存储内部32位int两个16位整数:

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); 
} 
相关问题