【问题标题】:Converting byte to a single int Android将字节转换为单个 int Android
【发布时间】:2014-03-15 21:58:10
【问题描述】:

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

int|位图

由于我需要传输最多 27 的 int,这意味着它适合单个字节,对吗?我当前的代码如下所示:

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 之间。我检查了所有其他答案,但找不到合适的解决方案..

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

【问题讨论】:

  • 字节是 8 位,八进制。将八进制转换为 int?
  • @zgc7009 嗯?我看不到“八进制”在这里进入图片的位置; “八进制”是“基数 8”,与“二进制”是“基数 2”和“十进制”是“基数 10”的方式相同;它与 byte 的内部表示无关,它使用 8 个 bits
  • 是的,读错了:P 还没有真正完成你之前正在做的事情...... + 一个漫长的夜晚。无论如何,我添加了一个答案,因为评论太多了
  • 这段代码中的ba 是什么? byte[]?
  • 我也不认为八进制可以在这种情况下以任何方式帮助我。是的,代码中显示的 ba 是一个字节,它从值为 1 的 int 转换为27. ba定义为:byte[] ba = new byte[1];

标签: java android bitmap bluetooth


【解决方案1】:

由于将字节转换为 int 是一种向下转换,因此您只需将字节分配给 int 变量即可。

int myInt = ba[0];

【讨论】:

    【解决方案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]);
            }
        }
    }
    

    我再次意识到这并不完全是一个答案,评论太多了。

    【讨论】:

    • 我明白你在说什么,但我的主要问题是如何将整数字节与字节数组中的位图字节分开。因为在接收端我想分别重构发送的整数和位图......谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-04
    • 2016-02-20
    • 1970-01-01
    • 1970-01-01
    • 2011-02-19
    相关资源
    最近更新 更多