有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将字节转换为单个整数

我正在实现一个蓝牙Android应用程序,图像从一个设备发送到另一个设备。发送位图的字节数组,并在接收端成功重建。但是,我需要将一个整数值与位图一起发送作为索引(以便接收器知道如何处理接收到的位图)。基本上我想以字节流的形式发送:

int |位图

因为我需要将整数转换为27,这意味着它可以放入一个字节,对吗?我当前的代码如下所示:

ba[0] = Integer.valueOf(drawableNumber).byteValue(); //drawableNumber value is between 1 and 27
 ByteArrayOutputStream bs = new ByteArrayOutputStream();  //create new output stream
 try {
     bs.write(ba);         //bytes of the integer
     bs.write(bitmapdata); //bytes of the bitmap
     bs.toByteArray()      // put everything into byte array
}

 mChatService.write(bs.toByteArray()); // that is where bytes are sent to another device

在接收器端:

 case MESSAGE_READ:
    readBuf = (byte[]) msg.obj;  // readBuf contains ALL the received bytes using .read method

所以我的问题是,如何重建整数和我发送的图像(基本上是一个字节到一个整数)?我设法单独重建位图,但我需要这个额外的整数值来知道如何处理接收到的图像。整数值将始终介于0和27之间。我检查了所有其他答案,但找不到合适的解决办法

编辑:主要问题是如何在字节数组中将整数字节与位图字节分开。因为在接收端,我想分别重建发送的整数和位图


共 (2) 个答案

  1. # 1 楼答案

    由于将字节转换为int是一种向下转换,因此可以将字节分配给int变量

    int myInt = ba[0];
    
  2. # 2 楼答案

    当我在java中尝试这一点时,它简单地告诉我在评论时我的想法。整数表示为字节(因此在您的例子中,它只是ba[0])。或者它应该基于你的代码。再多的话,这将是一个漫长的过程。这意味着它也是从缓冲区读取的第一个字节(或者应该读取)

    import java.io.ByteArrayOutputStream;
    
    
    public class TestClass {
        public static void main(String args[]){
            byte[] ba = new byte[10];
            int myInt = 13;
            ByteArrayOutputStream bs = new ByteArrayOutputStream();  //create new output stream
    
            try {
               bs.write(myInt);         //bytes of the integer
               ba = bs.toByteArray();      // put everything into byte array
            } finally{};
    
            for(int i = 0; i < ba.length; i++){
              System.out.println(i);
              System.out.println(ba[i]);
            }
        }
    }
    

    我再次意识到这并不是一个确切的答案,只是太多的评论