Short to Byte Conversion
I'm trying to convert a short type to a 2 byte type for storage in a byte array, here's a snippet that works well "so far".
if (type == "short")
{
size = data.size;
databuffer[index+1] = (byte)(data.numeric_data >> 8);
databuffer[index] = (byte)(data.numeric_data & 255);
return size;
}
Numeric_data is of type int. Everything worked fine until I processed 284 (decimal). It turns out that 284 -> 8 is equal to 1 instead of 4.
The main goal is to:
byte[0] = 28
byte[1] = 4
source to share
Just for fun:
public static byte[] ToByteArray(short s)
{
//return, if `short` can be cast to `byte` without overflow
if (s <= byte.MaxValue)
return new byte[] { (byte)s };
List<byte> bytes = new List<byte>();
byte b = 0;
//determine delta through the number of digits
short delta = (short)Math.Pow(10, s.ToString().Length - 3);
//as soon as byte can be not more than 3 digits length
for (int i = 0; i < 3; i++)
{
//take first 3 (or 2, or 1) digits from the high-order digit
short temp = (short)(s / delta);
if (temp > byte.MaxValue) //if it still too big
delta *= 10;
else //the byte is found, break the loop
{
b = (byte)temp;
break;
}
}
//add the found byte
bytes.Add(b);
//recursively search in the rest of the number
bytes.AddRange(ToByteArray((short)(s % delta)));
return bytes.ToArray();
}
this recursive method does what the OP wants with at least a positive value short
.
source to share
Why 284 >> 8
would you 4
?
Why 284
share in two bytes equal to 28
and 4
?
The binary representation 284
is equal 0000 0001 0001 1100
. As you can see, there are two bytes (eight bits) which are 0000 0001
( 256
decimal) and 0001 1100
( 28
decimal).
284 >> 8
- 1
( 0000 0001
), and rightly so.
284
must be split into two bytes equal to 256
and 24
.
Your conversion is correct!
source to share
If you insist:
short val = 284;
byte a = (byte)(val / 10);
byte b = (byte)(val % 10);
Denial of responsibility:
It doesn't make a lot of sense, but this is what you want. I assume you want values between 0 and 99. The logical challenge would be to use 100 as the denominator, not 10. But again, I have no idea what you want to do.
source to share