java中byte数组与int,long,short,float,char之间的转换

来源:互联网 发布:攻沙翅膀进阶数据 编辑:程序博客网 时间:2024/05/16 12:16

Java基本类型与byte数组之间相互转换,刚刚写的,还热着

package com.my.wxf4j.utils;

import java.nio.charset.Charset;

public class ByteUtil
{
    public static byte[] getBytes(short data)
    {
        byte[] bytes = new byte[2];
        bytes[0] = (byte) (data & 0xff);
        bytes[1] = (byte) ((data & 0xff00) >> 8);
        return bytes;
    }

    public static byte[] getBytes(char data)
    {
        byte[] bytes = new byte[2];
        bytes[0] = (byte) (data);
        bytes[1] = (byte) (data >> 8);
        return bytes;
    }

    public static byte[] getBytes(int data)
    {
        byte[] bytes = new byte[4];
        bytes[0] = (byte) (data & 0xff);
        bytes[1] = (byte) ((data & 0xff00) >> 8);
        bytes[2] = (byte) ((data & 0xff0000) >> 16);
        bytes[3] = (byte) ((data & 0xff000000) >> 24);
        return bytes;
    }

    public static byte[] getBytes(long data)
    {
        byte[] bytes = new byte[8];
        bytes[0] = (byte) (data & 0xff);
        bytes[1] = (byte) ((data >> 8) & 0xff);
        bytes[2] = (byte) ((data >> 16) & 0xff);
        bytes[3] = (byte) ((data >> 24) & 0xff);
        bytes[4] = (byte) ((data >> 32) & 0xff);
        bytes[5] = (byte) ((data >> 40) & 0xff);
        bytes[6] = (byte) ((data >> 48) & 0xff);
        bytes[7] = (byte) ((data >> 56) & 0xff);
        return bytes;
    }

    public static byte[] getBytes(float data)
    {
        int intBits = Float.floatToIntBits(data);
        return getBytes(intBits);
    }

    public static byte[] getBytes(double data)
    {
        long intBits = Double.doubleToLongBits(data);
        return getBytes(intBits);
    }

    public static byte[] getBytes(String data, String charsetName)
    {
        Charset charset = Charset.forName(charsetName);
        return data.getBytes(charset);
    }

    public static byte[] getBytes(String data)
    {
        return getBytes(data, "GBK");
    }

    
    public static short getShort(byte[] bytes)
    {
        return (short) ((0xff & bytes[0]) | (0xff00 & (bytes[1] << 8)));
    }

    public static char getChar(byte[] bytes)
    {
        return (char) ((0xff & bytes[0]) | (0xff00 & (bytes[1] << 8)));
    }

    public static int getInt(byte[] bytes)
    {
        return (0xff & bytes[0]) | (0xff00 & (bytes[1] << 8)) | (0xff0000 & (bytes[2] << 16)) | (0xff000000 & (bytes[3] << 24));
    }
   
    public static long getLong(byte[] bytes)
    {
        return(0xffL & (long)bytes[0]) | (0xff00L & ((long)bytes[1] << 8)) | (0xff0000L & ((long)bytes[2] << 16)) | (0xff000000L & ((long)bytes[3] << 24))
         | (0xff00000000L & ((long)bytes[4] << 32)) | (0xff0000000000L & ((long)bytes[5] << 40)) | (0xff000000000000L & ((long)bytes[6] << 48)) | (0xff00000000000000L & ((long)bytes[7] << 56));
    }

    public static float getFloat(byte[] bytes)
    {
        return Float.intBitsToFloat(getInt(bytes));
    }

    public static double getDouble(byte[] bytes)
    {
        long l = getLong(bytes);
        System.out.println(l);
        return Double.longBitsToDouble(l);
    }

    public static String getString(byte[] bytes, String charsetName)
    {
        return new String(bytes, Charset.forName(charsetName));
    }

    public static String getString(byte[] bytes)
    {
        return getString(bytes, "GBK");
    }

    
    public static void main(String[] args)
    {
        short s = 122;
        int i = 122;
        long l = 1222222;

        char c = 'a';

        float f = 122.22f;
        double d = 122.22;

        String string = "我是好孩子";
        System.out.println(s);
        System.out.println(i);
        System.out.println(l);
        System.out.println(c);
        System.out.println(f);
        System.out.println(d);
        System.out.println(string);

        System.out.println("**************");

        System.out.println(getShort(getBytes(s)));
        System.out.println(getInt(getBytes(i)));
        System.out.println(getLong(getBytes(l)));
        System.out.println(getChar(getBytes(c)));
        System.out.println(getFloat(getBytes(f)));
        System.out.println(getDouble(getBytes(d)));
        System.out.println(getString(getBytes(string)));
    }
}

我们都知道,在socket传输中,发送、者接收的数据都是 byte数组,而实际中我们会传输各种类型的数据,比如int,long,short间等等

这就需要我们在使用中完成byte类型和int,long,short,float之间的转换

转换的核心在于其他类型的数据每位所占的转换后所占的byte不同

下面给出相关的转换代码

首先说一下用的最多的Byte和int之间的转换

查看源代码
打印帮助
1/**
2*将32位的int值放到4字节的<a href="http://www.ztyhome.com/tag/byte/" title="查看 byte 中的全部文章" target="_blank">byte</a>[]里
3* @param num
4* @return
5*/
6public static <a href="http://www.ztyhome.com/tag/byte/"title="查看 byte 中的全部文章"target="_blank">byte</a>[] int2byteArray(int num) {
7   byte[] result = new byte[4];
8   result[0] = (byte)(num &gt;&gt;&gt; 24);//取最高8位放到0下标
9   result[1] = (byte)(num &gt;&gt;&gt; 16);//取次高8为放到1下标
10   result[2] = (byte)(num &gt;&gt;&gt; 8); //取次低8位放到2下标
11   result[3] = (byte)(num );      //取最低8位放到3下标
12   return result;
13}
14  
15/**
16* 将4字节的byte数组转成一个int值
17* @param b
18* @return
19*/
20public static int byteArray2int(byte[] b){
21    byte[] a = new byte[4];
22    int i = a.length - 1,j = b.length - 1;
23    for (; i &gt;= 0 ; i--,j--) {//从b的尾部(即int值的低位)开始copy数据
24        if(j &gt;= 0)
25            a[i] = b[j];
26        else
27            a[i] = 0;//如果b.length不足4,则将高位补0
28  }
29    int v0 = (a[0] &amp; 0xff) &lt;&lt; 24;//&amp;0xff将byte值无差异转成int,避免Java自动类型提升后,会保留高位的符号位
30    int v1 = (a[1] &amp; 0xff) &lt;&lt; 16;
31    int v2 = (a[2] &amp; 0xff) &lt;&lt; 8;
32    int v3 = (a[3] &amp; 0xff) ;
33    return v0 + v1 + v2 + v3;
34}

short和byte的互转

查看源代码
打印帮助
1/**
2* 转换short为byte
3*
4* @param b
5* @param s
6*            需要转换的short
7* @param index
8*/
9public static void putShort(byte b[], short s, int index) {
10     b[index + 1] = (byte) (s >> 8);
11     b[index + 0] = (byte) (s >> 0);
12}
13  
14/**
15* 通过byte数组取到short
16*
17* @param b
18* @param index
19*            第几位开始取
20* @return
21*/
22public static short getShort(byte[] b, int index) {
23      return (short) (((b[index + 1] << 8) | b[index + 0] & 0xff));
24}

byte和char类型的转换

查看源代码
打印帮助
1/**
2    * 字符到字节转换
3    *
4    * @param ch
5    * @return
6    */
7   publicstaticvoid putChar(byte[] bb, char ch, int index) {
8       int temp = (int) ch;
9       // byte[] b = new byte[2];
10       for(int i = 0; i < 2; i ++ ) {
11            // 将最高位保存在最低位
12           bb[index + i] =newInteger(temp & 0xff).byteValue();
13           temp = temp >> 8;// 向右移8位
14       }
15   }
16   /**
17    * 字节到字符转换
18    *
19    * @param b
20    * @return
21    */
22   publicstaticchar getChar(byte[] b, int index) {
23       int s = 0;
24       if(b[index + 1] > 0)
25           s += b[index + 1];
26       else
27           s += 256 + b[index + 0];
28       s *= 256;
29       if(b[index + 0] > 0)
30           s += b[index + 1];
31       else
32           s += 256 + b[index + 0];
33       char ch = (char) s;
34       returnch;
35   }

byte和float的转换

查看源代码
打印帮助
1/**
2 * float转换byte
3 *
4 * @param bb
5 * @param x
6 * @param index
7 */
8public static void putFloat(byte[] bb, float x, int index) {
9    // byte[] b = new byte[4];
10    int l = Float.floatToIntBits(x);
11    for(int i = 0; i < 4; i++) {
12        bb[index + i] =newInteger(l).byteValue();
13        l = l >> 8;
14    }
15}
16/**
17 * 通过byte数组取得float
18 *
19 * @param bb
20 * @param index
21 * @return
22 */
23public static float getFloat(byte[] b, int index) {
24    int l;
25    l = b[index + 0];
26    l &= 0xff;
27    l |= ((long) b[index + 1] << 8);
28    l &= 0xffff;
29    l |= ((long) b[index + 2] << 16);
30    l &= 0xffffff;
31    l |= ((long) b[index + 3] << 24);
32    returnFloat.intBitsToFloat(l);
33}

byte和double转换

查看源代码
打印帮助
1    /**
2     * double转换byte
3     *
4     * @param bb
5     * @param x
6     * @param index
7     */
8    publicstaticvoid putDouble(byte[] bb, double x, int index) {
9        // byte[] b = new byte[8];
10        long l = Double.doubleToLongBits(x);
11        for(int i = 0; i < 4; i++) {
12            bb[index + i] =newLong(l).byteValue();
13            l = l >> 8;
14        }
15    }
16  
17    /**
18     * 通过byte数组取得float
19     *
20     * @param bb
21     * @param index
22     * @return
23     */
24    publicstaticdouble getDouble(byte[] b, int index) {
25        long l;
26        l = b[0];
27        l &= 0xff;
28        l |= ((long) b[1] << 8);
29        l &= 0xffff;
30        l |= ((long) b[2] << 16);
31        l &= 0xffffff;
32        l |= ((long) b[3] << 24);
33        l &= 0xffffffffl;
34        l |= ((long) b[4] << 32);
35        l &= 0xffffffffffl;
36        l |= ((long) b[5] << 40);
37        l &= 0xffffffffffffl;
38        l |= ((long) b[6] << 48);
39        l &= 0xffffffffffffffl;
40        l |= ((long) b[7] << 56);
41        returnDouble.longBitsToDouble(l);
42    }
43}

稍微注意一下就能发现,各种类型与byte之间的转换主要是位数的差异,在转换过程中涉及到的算法也是移位,只要你理解了这个过程,那么数据传输过程涉及到byte和其他类型数据的转换就很简单了

原创粉丝点击