Konwertuj skrót na bajt [] w Javie

Jak mogę przekonwertować short (2 bajty) na tablicę bajtów w Javie, np.

short x = 233;
byte[] ret = new byte[2];

...
To powinno być coś takiego. Ale nie jestem pewien.
((0xFF << 8) & x) >> 0;

EDIT:

Możesz również użyć:

java.nio.ByteOrder.nativeOrder();

Aby dowiedzieć się, czy natywny porządek bitów jest duży czy mały. Ponadto z java.io.Bits pochodzi następujący kod:

  • byte (array/offset) to boolean
  • tablica bajtów do znaku
  • tablica bajtów na krótki
  • tablica bajtów do int
  • tablica bajtów do float
  • tablica bajtów na long
  • tablica bajtów do podwojenia
I visa versa.
Author: Hugh, 2010-02-03

9 answers

ret[0] = (byte)(x & 0xff);
ret[1] = (byte)((x >> 8) & 0xff);
 66
Author: Alexander Gessler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-02-02 23:56:26

Czystszym, aczkolwiek znacznie mniej wydajnym rozwiązaniem jest:

ByteBuffer buffer = ByteBuffer.allocate(2);
buffer.putShort(value);
return buffer.array();

Pamiętaj o tym, gdy w przyszłości będziesz musiał wykonać bardziej złożone transformacje bajtów. Bytebuffery są bardzo potężne.

 33
Author: Gili,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-02 18:13:12

Alternatywa, która jest bardziej efektywna:

    // Little Endian
    ret[0] = (byte) x;
    ret[1] = (byte) (x >> 8);

    // Big Endian
    ret[0] = (byte) (x >> 8);
    ret[1] = (byte) x;
 11
Author: David,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-25 12:19:54

Rozgryzłem to, its:

public static byte[] toBytes(short s) {
    return new byte[]{(byte)(s & 0x00FF),(byte)((s & 0xFF00)>>8)};
}
 7
Author: Hugh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-11 15:30:16

To zależy jak chcesz to reprezentować:

  • Big endian czy little endian? To określi, w jakiej kolejności umieścisz bajty.

  • Czy chcesz użyć dopełniacza 2 lub innego sposobu reprezentowania liczby ujemnej? Należy użyć schematu, który ma taki sam zakres jak krótki w Javie, aby mieć mapowanie 1-to-1.

Dla big endian transformacja powinna być zgodna z: ret[0] = x/256; ret[1] = x%256;

 3
Author: abc,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-02-02 23:59:18
public short bytesToShort(byte[] bytes) {
     return ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getShort();
}

public byte[] shortToBytes(short value) {
    byte[] returnByteArray = new byte[2];
    returnByteArray[0] = (byte) (value & 0xff);
    returnByteArray[1] = (byte) ((value >>> 8) & 0xff);
    return returnByteArray;
}
 1
Author: Scott Izu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-08 06:27:04

Kilka metod zostało tutaj wymienionych. Ale który jest najlepszy? Poniżej przedstawiamy dowód, że następujące 3 podejścia dają taki sam wynik dla wszystkich wartości short

  // loops through all the values of a Short
  short i = Short.MIN_VALUE;
  do
  {
    // method 1: A SIMPLE SHIFT
    byte a1 = (byte) (i >> 8);
    byte a2 = (byte) i;

    // method 2: AN UNSIGNED SHIFT
    byte b1 = (byte) (i >>> 8);
    byte b2 = (byte) i;

    // method 3: SHIFT AND MASK
    byte c1 = (byte) (i >> 8 & 0xFF);
    byte c2 = (byte) (i & 0xFF);

    if (a1 != b1 || a1 != c1 ||
        a2 != b2 || a2 != c2)
    {
      // this point is never reached !!
    }
  } while (i++ != Short.MAX_VALUE);

Wniosek: mniej znaczy więcej ?

byte b1 = (byte) (s >> 8);
byte b2 = (byte) s;

(Jak już wspomniano w innych odpowiedziach, uważaj na LE / BE ).

 1
Author: bvdb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-17 11:26:40

Metoda konwersji krótkich na bajty w Kotlinie działa dla mnie:

 fun toBytes(s: Short): ByteArray {
    return byteArrayOf((s.toInt() and 0x00FF).toByte(), ((s.toInt() and 0xFF00) shr (8)).toByte())
}
 1
Author: Serg Burlaka,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-20 11:45:32

Skrót do bajtu

short x=17000;    
byte res[]=new byte[2];    
res[i]= (byte)(((short)(x>>7)) & ((short)0x7f) | 0x80 );    
res[i+1]= (byte)((x & ((short)0x7f)));

Byte to short

short x=(short)(128*((byte)(res[i] &(byte)0x7f))+res[i+1]);
 0
Author: chitrendra chaudhary,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-17 05:21:31