Convert Integer into Byte Array (Java)

Convert integer into byte array (Java)

Have a look at the ByteBuffer class.

ByteBuffer b = ByteBuffer.allocate(4);
//b.order(ByteOrder.BIG_ENDIAN); // optional, the initial order of a byte buffer is always BIG_ENDIAN.
b.putInt(0xAABBCCDD);

byte[] result = b.array();

Setting the byte order ensures that result[0] == 0xAA, result[1] == 0xBB, result[2] == 0xCC and result[3] == 0xDD.

Or alternatively, you could do it manually:

byte[] toBytes(int i)
{
byte[] result = new byte[4];

result[0] = (byte) (i >> 24);
result[1] = (byte) (i >> 16);
result[2] = (byte) (i >> 8);
result[3] = (byte) (i /*>> 0*/);

return result;
}

The ByteBuffer class was designed for such dirty hands tasks though. In fact the private java.nio.Bits defines these helper methods that are used by ByteBuffer.putInt():

private static byte int3(int x) { return (byte)(x >> 24); }
private static byte int2(int x) { return (byte)(x >> 16); }
private static byte int1(int x) { return (byte)(x >> 8); }
private static byte int0(int x) { return (byte)(x >> 0); }

Java integer to byte array

using Java NIO's ByteBuffer is very simple:

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

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

output:


0x65 0x10 0xf3 0x29

How to convert int to byte[]?

You forgot to flip() your buffer after putting data in.

After you've put the int in the buffer, the position is at the end of the buffer. Trying to read data results in BufferUnderflowException (not overflow) since there are no bytes left to read in the buffer.

How to Convert Int to Unsigned Byte and Back

A byte is always signed in Java. You may get its unsigned value by binary-anding it with 0xFF, though:

int i = 234;
byte b = (byte) i;
System.out.println(b); // -22
int i2 = b & 0xFF;
System.out.println(i2); // 234

Java - Convert int to Byte Array of 4 Bytes?

You can convert yourInt to bytes by using a ByteBuffer like this:

return ByteBuffer.allocate(4).putInt(yourInt).array();

Beware that you might have to think about the byte order when doing so.

Converting integer array to byte array

convert int to byte[].
create this function:

byte[] toBytes(int i)
{
byte[] result = new byte[4];

result[0] = (byte) (i >> 24);
result[1] = (byte) (i >> 16);
result[2] = (byte) (i >> 8);
result[3] = (byte) (i /*>> 0*/);

return result;
}

Run in a loop on your int[], for each cell call to the function and add result to an array of bytes.

How to convert int[] to byte[]

As Brian says, you need to work out how what sort of conversion you need.

Do you want to save it as a "normal" image file (jpg, png etc)?

If so, you should probably use the Java Image I/O API.

If you want to save it in a "raw" format, the order in which to write the bytes must be specified, and then use an IntBuffer and NIO.

As an example of using a ByteBuffer/IntBuffer combination:

import java.nio.*;
import java.net.*;

class Test
{
public static void main(String [] args)
throws Exception // Just for simplicity!
{
int[] data = { 100, 200, 300, 400 };

ByteBuffer byteBuffer = ByteBuffer.allocate(data.length * 4);
IntBuffer intBuffer = byteBuffer.asIntBuffer();
intBuffer.put(data);

byte[] array = byteBuffer.array();

for (int i=0; i < array.length; i++)
{
System.out.println(i + ": " + array[i]);
}
}
}

List of Integers into byte array

There is byteValue() method available in Number class. Number is extended by Integer, Double, Float etc.

List<Integer> list = getNumbers();

Iterator<Integer> iterator = list.iterator();

while(iterator.hasNext())
{
Integer i = iterator.next()
byteArray[index] = i.byteValue();
}

You can also use java.nio.MappedByteBuffer class for block copy. see http://docs.oracle.com/javase/7/docs/api/java/nio/MappedByteBuffer.html.

MappedByteBuffer is equivalent to Buffer.BlockCopy() in .NET

Convert an integer to a byte array

I agree with Brainstorm's approach: assuming that you're passing a machine-friendly binary representation, use the encoding/binary library. The OP suggests that binary.Write() might have some overhead. Looking at the source for the implementation of Write(), I see that it does some runtime decisions for maximum flexibility.

func Write(w io.Writer, order ByteOrder, data interface{}) error {
// Fast path for basic types.
var b [8]byte
var bs []byte
switch v := data.(type) {
case *int8:
bs = b[:1]
b[0] = byte(*v)
case int8:
bs = b[:1]
b[0] = byte(v)
case *uint8:
bs = b[:1]
b[0] = *v
...

Right? Write() takes in a very generic data third argument, and that's imposing some overhead as the Go runtime then is forced into encoding type information. Since Write() is doing some runtime decisions here that you simply don't need in your situation, maybe you can just directly call the encoding functions and see if it performs better.

Something like this:

package main

import (
"encoding/binary"
"fmt"
)

func main() {
bs := make([]byte, 4)
binary.LittleEndian.PutUint32(bs, 31415926)
fmt.Println(bs)
}

Let us know how this performs.

Otherwise, if you're just trying to get an ASCII representation of the integer, you can get the string representation (probably with strconv.Itoa) and cast that string to the []byte type.

package main

import (
"fmt"
"strconv"
)

func main() {
bs := []byte(strconv.Itoa(31415926))
fmt.Println(bs)
}


Related Topics



Leave a reply



Submit