How to Convert Int[] to Byte[]

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); }

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

C# int to byte[]

The RFC is just trying to say that a signed integer is a normal 4-byte integer with bytes ordered in a big-endian way.

Now, you are most probably working on a little-endian machine and BitConverter.GetBytes() will give you the byte[] reversed. So you could try:

int intValue;
byte[] intBytes = BitConverter.GetBytes(intValue);
Array.Reverse(intBytes);
byte[] result = intBytes;

For the code to be most portable, however, you can do it like this:

int intValue;
byte[] intBytes = BitConverter.GetBytes(intValue);
if (BitConverter.IsLittleEndian)
Array.Reverse(intBytes);
byte[] result = intBytes;

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]);
}
}
}

Why does bytes(n) create a length n byte string instead of converting n to a binary representation?

Python 3.5+ introduces %-interpolation (printf-style formatting) for bytes:

>>> b'%d\r\n' % 3
b'3\r\n'

See PEP 0461 -- Adding % formatting to bytes and bytearray.

On earlier versions, you could use str and .encode('ascii') the result:

>>> s = '%d\r\n' % 3
>>> s.encode('ascii')
b'3\r\n'

Note: It is different from what int.to_bytes produces:

>>> n = 3
>>> n.to_bytes((n.bit_length() + 7) // 8, 'big') or b'\0'
b'\x03'
>>> b'3' == b'\x33' != b'\x03'
True

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.

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)
}

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.

Converting from byte to int in Java

Your array is of byte primitives, but you're trying to call a method on them.

You don't need to do anything explicit to convert a byte to an int, just:

int i=rno[0];

...since it's not a downcast.

Note that the default behavior of byte-to-int conversion is to preserve the sign of the value (remember byte is a signed type in Java). So for instance:

byte b1 = -100;
int i1 = b1;
System.out.println(i1); // -100

If you were thinking of the byte as unsigned (156) rather than signed (-100), as of Java 8 there's Byte.toUnsignedInt:

byte b2 = -100; // Or `= (byte)156;`
int = Byte.toUnsignedInt(b2);
System.out.println(i2); // 156

Prior to Java 8, to get the equivalent value in the int you'd need to mask off the sign bits:

byte b2 = -100; // Or `= (byte)156;`
int i2 = (b2 & 0xFF);
System.out.println(i2); // 156

Just for completeness #1: If you did want to use the various methods of Byte for some reason (you don't need to here), you could use a boxing conversion:

Byte b = rno[0]; // Boxing conversion converts `byte` to `Byte`
int i = b.intValue();

Or the Byte constructor:

Byte b = new Byte(rno[0]);
int i = b.intValue();

But again, you don't need that here.


Just for completeness #2: If it were a downcast (e.g., if you were trying to convert an int to a byte), all you need is a cast:

int i;
byte b;

i = 5;
b = (byte)i;

This assures the compiler that you know it's a downcast, so you don't get the "Possible loss of precision" error.

Converting an int[] to byte[] in C#

If you want a bitwise copy, i.e. get 4 bytes out of one int, then use Buffer.BlockCopy:

byte[] result = new byte[intArray.Length * sizeof(int)];
Buffer.BlockCopy(intArray, 0, result, 0, result.Length);

Don't use Array.Copy, because it will try to convert and not just copy. See the remarks on the MSDN page for more info.



Related Topics



Leave a reply



Submit