java的char 转byte

java中的char类型即可以存储英文字母也可以存储汉字,汉字在java中使用Unicode编码占两个字节。char转byte数组的方法如下:

public static byte[] charToByte(char c) {
    byte[] b = new byte[2];
    b[0] = (byte) ((c & 0xFF00) >> 8);
    b[1] = (byte) (c & 0xFF);
    return b;
}

另外附上其它几种数字类型和byte类型之间互相转换方法


    public static byte[] float2byte(float f) {
        // 把float转换为byte[]
        int fbit = Float.floatToIntBits(f);
        byte[] b = new byte[4];
        for (int i = 0; i < 4; i++) {
            b[i] = (byte) (fbit >> (24 - i * 8));
        }
        // 翻转数组
        int len = b.length;
        // 建立一个与源数组元素类型相同的数组
        byte[] dest = new byte[len];
        // 为了防止修改源数组,将源数组拷贝一份副本
        System.arraycopy(b, 0, dest, 0, len);
        byte temp;
        // 将顺位第i个与倒数第i个交换
        for (int i = 0; i < len / 2; ++i) {
            temp = dest[i];
            dest[i] = dest[len - i - 1];
            dest[len - i - 1] = temp;
        }
        return dest;
    }

    public static float getFloat(Byte[] b) {
        int accum = 0;

        accum = accum | (b[0] & 0xff) << 0;

        accum = accum | (b[1] & 0xff) << 8;

        accum = accum | (b[2] & 0xff) << 16;

        accum = accum | (b[3] & 0xff) << 24;

        return Float.intBitsToFloat(accum);

    }

   
    public static float getLong(Byte[] b) {
        long accum = 0;

        accum = accum | (b[0] & 0xff) << 0;

        accum = accum | (b[1] & 0xff) << 8;

        accum = accum | (b[2] & 0xff) << 16;

        accum = accum | (b[3] & 0xff) << 24;

        return accum;

    }
    
    public static int getInt(Byte[] b) {
        int accum = 0;

        accum = accum | (b[0] & 0xff) << 0;

        accum = accum | (b[1] & 0xff) << 8;

        return accum;

    }

  
    public static byte[] short2byte(short s) {
        byte[] result = new byte[2];
        result[0]=(byte)((s >> 8) & 0xFF);
        result[1]=(byte)((s >> 0) & 0xFF);
        return result;
    }


    public static short byte2short(byte[] b){
        short l = 0;
        for (int i = 0; i < 2; i++) {
            l<<=8; //<<=和我们的 +=是一样的,意思就是 l = l << 8
            l |= (b[i] & 0xff); //和上面也是一样的  l = l | (b[i]&0xff)
        }
        return l;
    }

    public static short byte2short(Byte[] b){
        short l = 0;
        for (int i = 0; i < 2; i++) {
            l<<=8; //<<=和我们的 +=是一样的,意思就是 l = l << 8
            l |= (b[i] & 0xff); //和上面也是一样的  l = l | (b[i]&0xff)
        }
        return l;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值