Java 如何将 int[] 转换为 byte[]
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1086054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert int[] to byte[]
提问by Niko Gamulin
I have an array of integers which represent a RGB image and would like to convert it to a byte array and save it to a file.
我有一个表示 RGB 图像的整数数组,并希望将其转换为字节数组并将其保存到文件中。
What's the best way to convert an array of integers to the array of bytes in Java?
在 Java 中将整数数组转换为字节数组的最佳方法是什么?
采纳答案by Jon Skeet
As Briansays, 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)?
您想将其另存为“普通”图像文件(jpg、png 等)吗?
If so, you should probably use the Java Image I/OAPI.
如果是这样,您可能应该使用Java Image I/OAPI。
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.
如果要将其保存为“原始”格式,则必须指定写入字节的顺序,然后使用IntBuffer
和 NIO。
As an example of using a ByteBuffer/IntBuffer combination:
作为使用 ByteBuffer/IntBuffer 组合的示例:
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]);
}
}
}
回答by Brian Agnew
You need to decide how you convert 1 integer to a set of bytes first.
您需要先决定如何将 1 个整数转换为一组字节。
Most probably (?) 1 integer to 4 bytes, and use the shift (>>
or <<
) operators to get each byte out (watch that byte ordering!). Copy to a byte array 4 times the length of the integer array.
最有可能是 (?) 1 个整数到 4 个字节,并使用移位 (>>
或<<
) 运算符来获取每个字节(注意字节顺序!)。复制到整数数组长度的 4 倍的字节数组。
回答by Prabhu R
Maybe use this method
也许用这个方法
byte[] integersToBytes(int[] values)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
for(int i=0; i < values.length; ++i)
{
dos.writeInt(values[i]);
}
return baos.toByteArray();
}
回答by dfa
if your intent is to save to file you maybe want to save directly in a file using FileOutputStream.write:
如果您的意图是保存到文件,您可能希望使用 FileOutputStream.write 直接保存在文件中:
OutputStream os = new FileOutputStream("aa");
int[] rgb = { 0xff, 0xff, 0xff };
for (int c : rgb) {
os.write(c);
}
os.close();
since it:
因为它:
Writes the specified byte to this output stream. The general contract for write is that one byte is written to the output stream. The byte to be written is the eight low-order bits of the argument b. The 24 high-order bits of b are ignored.
将指定的字节写入此输出流。write 的一般约定是将一个字节写入输出流。要写入的字节是参数 b 的低 8 位。b 的 24 个高位被忽略。
回答by ncn32
I created this code and it's working pretty well:
我创建了这段代码,它运行良好:
int IntToByte(byte arrayDst[], int arrayOrg[], int maxOrg){
int i;
int idxDst;
int maxDst;
//
maxDst = maxOrg*4;
//
if (arrayDst==null)
return 0;
if (arrayOrg==null)
return 0;
if (arrayDst.length < maxDst)
return 0;
if (arrayOrg.length < maxOrg)
return 0;
//
idxDst = 0;
for (i=0; i<maxOrg; i++){
// Copia o int, byte a byte.
arrayDst[idxDst] = (byte)(arrayOrg[i]);
idxDst++;
arrayDst[idxDst] = (byte)(arrayOrg[i] >> 8);
idxDst++;
arrayDst[idxDst] = (byte)(arrayOrg[i] >> 16);
idxDst++;
arrayDst[idxDst] = (byte)(arrayOrg[i] >> 24);
idxDst++;
}
//
return idxDst;
}
int ByteToInt(int arrayDst[], byte arrayOrg[], int maxOrg){
int i;
int v;
int idxOrg;
int maxDst;
//
maxDst = maxOrg/4;
//
if (arrayDst==null)
return 0;
if (arrayOrg==null)
return 0;
if (arrayDst.length < maxDst)
return 0;
if (arrayOrg.length < maxOrg)
return 0;
//
idxOrg = 0;
for (i=0; i<maxDst; i++){
arrayDst[i] = 0;
//
v = 0x000000FF & arrayOrg[idxOrg];
arrayDst[i] = arrayDst[i] | v;
idxOrg++;
//
v = 0x000000FF & arrayOrg[idxOrg];
arrayDst[i] = arrayDst[i] | (v << 8);
idxOrg++;
//
v = 0x000000FF & arrayOrg[idxOrg];
arrayDst[i] = arrayDst[i] | (v << 16);
idxOrg++;
//
v = 0x000000FF & arrayOrg[idxOrg];
arrayDst[i] = arrayDst[i] | (v << 24);
idxOrg++;
}
//
return maxDst;
}
回答by ncn32
I would use 'DataOutputStream' with 'ByteArrayOutputStream'.
我会将“DataOutputStream”与“ByteArrayOutputStream”一起使用。
public final class Converter {
private static final int BYTES_IN_INT = 4;
private Converter() {}
public static byte [] convert(int [] array) {
if (isEmpty(array)) {
return new byte[0];
}
return writeInts(array);
}
public static int [] convert(byte [] array) {
if (isEmpty(array)) {
return new int[0];
}
return readInts(array);
}
private static byte [] writeInts(int [] array) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream(array.length * 4);
DataOutputStream dos = new DataOutputStream(bos);
for (int i = 0; i < array.length; i++) {
dos.writeInt(array[i]);
}
return bos.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static int [] readInts(byte [] array) {
try {
ByteArrayInputStream bis = new ByteArrayInputStream(array);
DataInputStream dataInputStream = new DataInputStream(bis);
int size = array.length / BYTES_IN_INT;
int[] res = new int[size];
for (int i = 0; i < size; i++) {
res[i] = dataInputStream.readInt();
}
return res;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
public class ConverterTest {
@Test
public void convert() {
final int [] array = {-1000000, 24000, -1, 40};
byte [] bytes = Converter.convert(array);
int [] array2 = Converter.convert(bytes);
assertTrue(ArrayUtils.equals(array, array2));
System.out.println(Arrays.toString(array));
System.out.println(Arrays.toString(bytes));
System.out.println(Arrays.toString(array2));
}
}
Prints:
印刷:
[-1000000, 24000, -1, 40]
[-1, -16, -67, -64, 0, 0, 93, -64, -1, -1, -1, -1, 0, 0, 0, 40]
[-1000000, 24000, -1, 40]