Java: как разбить целое число (шестнадцатеричное значение) на массив байтов [duplicate]

Еще один подход к возврату значения из асинхронной функции - передать объект, который сохранит результат от асинхронной функции.

Вот пример того же:

var async = require("async");

// This wires up result back to the caller
var result = {};
var asyncTasks = [];
asyncTasks.push(function(_callback){
    // some asynchronous operation
    $.ajax({
        url: '...',
        success: function(response) {
            result.response = response;
            _callback();
        }
    });
});

async.parallel(asyncTasks, function(){
    // result is available after performing asynchronous operation
    console.log(result)
    console.log('Done');
});

Я использую объект result для хранения значения во время асинхронной операции. Это позволяет получить результат даже после асинхронного задания.

Я использую этот подход много. Мне было бы интересно узнать, насколько хорошо этот подход работает, когда задействован результат обратно через последовательные модули.

150
задан ROMANIA_engineer 16 December 2014 в 00:36
поделиться

13 ответов

с использованием Java NIO's ByteBuffer очень прост:

byte[] bytes = ByteBuffer.allocate(4).putInt(1695609641).array();

for (byte b : bytes) {
   System.out.format("0x%x ", b);
}

output:

0x65 0x10 0xf3 0x29 
256
ответ дан dfa 27 August 2018 в 07:53
поделиться

Использование Guava :

byte[] bytearray = Ints.toByteArray(1695609641);
17
ответ дан Aleksandr Dubinsky 27 August 2018 в 07:53
поделиться
integer & 0xFF

для первого байта

(integer >> 8) & 0xFF

для второго и цикла и т. д., записывая в предварительно выделенный массив байтов. К сожалению, немного грязно.

0
ответ дан Brian Agnew 27 August 2018 в 07:53
поделиться
byte[] conv = new byte[4];
conv[3] = (byte) input & 0xff;
input >>= 8;
conv[2] = (byte) input & 0xff;
input >>= 8;
conv[1] = (byte) input & 0xff;
input >>= 8;
conv[0] = (byte) input;
7
ответ дан Carl Smotricz 27 August 2018 в 07:53
поделиться

Как насчет:

public static final byte[] intToByteArray(int value) {
    return new byte[] {
            (byte)(value >>> 24),
            (byte)(value >>> 16),
            (byte)(value >>> 8),
            (byte)value};
}

Идея не моя . Я взял это из некоторого сообщения на dzone.com .

127
ответ дан Grzegorz Oledzki 27 August 2018 в 07:53
поделиться

Ниже приведенные ниже фрагменты работают, по крайней мере, для отправки int по UDP.

int в байтовый массив:

public byte[] intToBytes(int my_int) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutput out = new ObjectOutputStream(bos);
    out.writeInt(my_int);
    out.close();
    byte[] int_bytes = bos.toByteArray();
    bos.close();
    return int_bytes;
}

массив байтов в int:

public int bytesToInt(byte[] int_bytes) throws IOException {
    ByteArrayInputStream bis = new ByteArrayInputStream(int_bytes);
    ObjectInputStream ois = new ObjectInputStream(bis);
    int my_int = ois.readInt();
    ois.close();
    return my_int;
}
4
ответ дан HaoQi Li 27 August 2018 в 07:53
поделиться

Как правило, вы хотели бы преобразовать этот массив обратно в int в более поздней точке, вот методы для преобразования массива int в массив байтов и наоборот:

public static byte[] convertToByteArray(final int[] pIntArray)
{
    final byte[] array = new byte[pIntArray.length * 4];
    for (int j = 0; j < pIntArray.length; j++)
    {
        final int c = pIntArray[j];
        array[j * 4] = (byte)((c & 0xFF000000) >> 24);
        array[j * 4 + 1] = (byte)((c & 0xFF0000) >> 16);
        array[j * 4 + 2] = (byte)((c & 0xFF00) >> 8);
        array[j * 4 + 3] = (byte)(c & 0xFF);
    }
    return array;
}

public static int[] convertToIntArray(final byte[] pByteArray)
{
    final int[] array = new int[pByteArray.length / 4];
    for (int i = 0; i < array.length; i++)
        array[i] = (((int)(pByteArray[i * 4]) << 24) & 0xFF000000) |
                (((int)(pByteArray[i * 4 + 1]) << 16) & 0xFF0000) |
                (((int)(pByteArray[i * 4 + 2]) << 8) & 0xFF00) |
                ((int)(pByteArray[i * 4 + 3]) & 0xFF);
    return array;
}

Обратите внимание, что из-за распространения знака и т. Д. При преобразовании обратно в int

необходимы «& amp; 0xFF ...»,
1
ответ дан jytou 27 August 2018 в 07:53
поделиться
public static byte[] intToBytes(int x) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(bos);
    out.writeInt(x);
    out.close();
    byte[] int_bytes = bos.toByteArray();
    bos.close();
    return int_bytes;
}
4
ответ дан lyon819 27 August 2018 в 07:53
поделиться

BigInteger.valueOf(1695609641).toByteArray()

39
ответ дан Marijn 27 August 2018 в 07:53
поделиться

Класс org.apache.hadoop.hbase.util.Bytes имеет кучу удобных методов преобразования byte [], но вы можете не захотеть добавить всю банку HBase в свой проект именно для этой цели. Удивительно, что не только такой метод пропускает AFAIK из JDK, но также и из очевидных libs, таких как commons io.

1
ответ дан mlohbihler 27 August 2018 в 07:53
поделиться

Если вы используете apache-commons

public static byte[] toByteArray(int value) {
    byte result[] = new byte[4];
    return Conversion.intToByteArray(value, 0, result, 0, 4);
}
0
ответ дан Neeraj 27 August 2018 в 07:53
поделиться

Моя попытка:

public static byte[] toBytes(final int intVal, final int... intArray) {
    if (intArray == null || (intArray.length == 0)) {
        return ByteBuffer.allocate(4).putInt(intVal).array();
    } else {
        final ByteBuffer bb = ByteBuffer.allocate(4 + (intArray.length * 4)).putInt(intVal);
        for (final int val : intArray) {
            bb.putInt(val);
        }
        return bb.array();
    }
}

С ее помощью вы можете сделать это:

byte[] fourBytes = toBytes(0x01020304);
byte[] eightBytes = toBytes(0x01020304, 0x05060708);

Полный класс находится здесь: https://gist.github.com / superbob / 6548493 , он поддерживает инициализацию от коротких или длинных

byte[] eightBytesAgain = toBytes(0x0102030405060708L);
1
ответ дан superbob 27 August 2018 в 07:53
поделиться
byte[] IntToByteArray( int data ) {

byte[] result = new byte[4];

result[0] = (byte) ((data & 0xFF000000) >> 24);
result[1] = (byte) ((data & 0x00FF0000) >> 16);
result[2] = (byte) ((data & 0x0000FF00) >> 8);
result[3] = (byte) ((data & 0x000000FF) >> 0);

return result;
}
19
ответ дан МоеИмя Неизвестно 27 August 2018 в 07:53
поделиться
Другие вопросы по тегам:

Похожие вопросы: