Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good way to convert between short and bytes?

Tags:

c#

.net

byte

short

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?

like image 726
RCIX Avatar asked Sep 18 '09 04:09

RCIX


People also ask

Which of the following ways is correct to convert a byte into long object?

The BigInteger class has a longValue() method to convert a byte array to a long value: long value = new BigInteger(bytes).

How do you represent 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.

How do you convert bytes to numbers?

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.


2 Answers

Use BitConverter

short number = 42;
byte[] numberBytes = BitConverter.GetBytes(number);
short converted = BitConverter.ToInt16(numberBytes);
like image 111
TJB Avatar answered Oct 22 '22 13:10

TJB


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);
}
like image 25
Ates Goral Avatar answered Oct 22 '22 15:10

Ates Goral