I need to take pairs of bytes in, and output shorts, and take shorts in and output pairs of bytes. Here are the functions i've devised for such a purpose:
static short ToShort(short byte1, short byte2)
{
short number = (short)byte2;
number <<= 4;
number += (short)byte1;
return number;
}
static void FromShort(short number, out byte byte1, out byte byte2)
{
byte byte2 = (byte)(number >> 4);
short tempByte = (short)byte2 << 4;
byte byte1 = (byte)(number - tempByte);
}
I think this is correct but i'm not sure. If this isn't the right way to do it, what is? is there a way to do this already in the framework?
The BigInteger class has a longValue() method to convert a byte array to a long value: long value = new BigInteger(bytes).
A byte is a group of 8 bits. A bit is the most basic unit and can be either 1 or 0. A byte is not just 8 values between 0 and 1, but 256 (28) different combinations (rather permutations) ranging from 00000000 via e.g. 01010101 to 11111111 . Thus, one byte can represent a decimal number between 0(00) and 255.
A byte value can be interchanged to an int value using the int. from_bytes() function. The int. from_bytes() function takes bytes, byteorder, signed, * as parameters and returns the integer represented by the given array of bytes.
Use BitConverter
short number = 42;
byte[] numberBytes = BitConverter.GetBytes(number);
short converted = BitConverter.ToInt16(numberBytes);
Shorter version (also shifting 8 bits instead of 4):
static short ToShort(short byte1, short byte2)
{
return (byte2 << 8) + byte1;
}
static void FromShort(short number, out byte byte1, out byte byte2)
{
byte2 = (byte)(number >> 8);
byte1 = (byte)(number & 255);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With