Un buon modo per convertire tra short e byte?
Domanda
Devo inserire coppie di byte e cortocircuiti in uscita, nonché cortocircuiti e coppie in uscita di byte. Ecco le funzioni che ho ideato per tale scopo:
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);
}
Penso che sia corretto ma non ne sono sicuro. Se questo non è il modo giusto per farlo, che cos'è? c'è un modo per farlo già nel quadro?
Soluzione
Versione più breve (anche spostando 8 bit anziché 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);
}
Altri suggerimenti
Usa BitConverter
short number = 42;
byte[] numberBytes = BitConverter.GetBytes(number);
short converted = BitConverter.ToInt16(numberBytes);
I byte sono 8 bit, non 4, quindi lo spostamento è disattivato. Hai anche dichiarato le variabili locali nella seconda funzione in modo da non finire per scrivere i parametri out
come intendi. È anche più chiaro / migliore se ti limiti alle operazioni bit per bit ( & amp;
, |
e ~
) ove possibile.
static short ToShort(byte byte1, byte byte2)
{
return (short) ((byte2 << 8) | (byte1 << 0));
}
static void FromShort(short number, out byte byte1, out byte byte2)
{
byte2 = (byte) (number >> 8);
byte1 = (byte) (number >> 0);
}
Nota che gli spostamenti sinistro e destro di zero non sono necessari, a rigor di termini. Ho appena messo quelli per simmetria. Inoltre, personalmente ti consiglio di imparare il freddo aritmetico bit per bit e di saltare a scrivere funzioni di supporto come queste. Non c'è bisogno di nascondere i dettagli con qualcosa di così fondamentale, IMHO.
Se vuoi prendere byte ... prendi byte; e i tuoi turni sono disattivati ??e |
sarebbe più intuitivo:
static short ToShort(byte byte1, byte byte2)
{ // using Int32 because that is what all the operations return anyway...
return (short)((((int)byte1) << 8) | (int)byte2);
}
static void FromShort(short number, out byte byte1, out byte byte2)
{
byte1 = (byte)(number >> 8); // to treat as same byte 1 from above
byte2 = (byte)number;
}
System.BitConverter