在Android中将int转换为字节 [英] Converting int to byte in Android

查看:123
本文介绍了在Android中将int转换为字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实际上,我需要通过 bluetooth传输整数值以及位图 / code> ..现在我的问题是我需要将整数传输为 字节值。.
可以转换 int 作为 byte 值..并以 integer 的形式检索它...我尝试了 byteValue() casting 之类的东西,但它没有用。如果我的方法是正确的,请帮助我解决这个问题或以其他方式说出来。

Actually I need to transfer the integer value along with the bitmap via bluetooth.. Now my problem is I need to transfer the integer as single byte value.. Is tat possible to convert int as single byte value.. and retrieve it as a integer there... I tried byteValue() and the casting thing but its not usefull.. If my approach is right just help me out with this or say some other way.

(每次使用投射时,它都返回65535)

(Each time when I am using casting then it's returning as 65535)

推荐答案

这又如何?

public static byte[] intToByteArray(int a)
{
    byte[] ret = new byte[4];
    ret[3] = (byte) (a & 0xFF);   
    ret[2] = (byte) ((a >> 8) & 0xFF);   
    ret[1] = (byte) ((a >> 16) & 0xFF);   
    ret[0] = (byte) ((a >> 24) & 0xFF);
    return ret;
}

public static int byteArrayToInt(byte[] b)
{
    return (b[3] & 0xFF) + ((b[2] & 0xFF) << 8) + ((b[1] & 0xFF) << 16) + ((b[0] & 0xFF) << 24);
}

这篇关于在Android中将int转换为字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆