socket编程 各种类型转换成字节数组(java)

       socket编程采用的就是tcp/ip网络协议。

      下面是java开发中一些常用的类型转换的方法:

      

    //将int类型转换成字节数组 (高位在后,低位在前的顺序) 大段序
    public static byte[] intToByte(int i) {  
        byte[] targets = new byte[4];  
        targets[0] = (byte) (i & 0xFF);  
        targets[1] = (byte) (i >> 8 & 0xFF);  
        targets[2] = (byte) (i >> 16 & 0xFF);  
        targets[3] = (byte) (i >> 24 & 0xFF);  
        return targets;  
    }  

     

//将int类型转换成字节数组 (高位在前,低位在后的顺序) 小段序
    public static byte[] intToByte2(int i) {  
        byte[] targets = new byte[4];  
        targets[3] = (byte) (i & 0xFF);  
        targets[2] = (byte) (i >> 8 & 0xFF);  
        targets[1] = (byte) (i >> 16 & 0xFF);  
        targets[0] = (byte) (i >> 24 & 0xFF);  
        return targets;  
    } 


 
    //将long类型转换成byte[]数组  (大端序,低位在前,高位在后)
    public static byte[] longToByteArray(long s) {
        byte[] targets = new byte[8];
        for (int i = 0; i < 8; i++) {
            int offset = (targets.length - 1 - i) * 8;
            targets[7-i] = (byte) ((s >>> offset) & 0xff);
        }
        return targets;
    }



 //byte数组中取int数值,本方法适用于(高位在前,低位在后)的顺序。小段序
    public static int bytesToInt2(byte[] src, int offset) {  
         int value;    
         value = (int) ( ((src[offset] & 0xFF)<<24)  
                 |((src[offset+1] & 0xFF)<<16)  
                 |((src[offset+2] & 0xFF)<<8)  
                 |(src[offset+3] & 0xFF));  
         return value;  
         
    }


  // byte数组中取int数值,本方法适用于(高位在后,低位在前)的顺序。 大段序
    
   public static int bytesToInt(byte[] src, int offset) {  
      int value;    
      value = (int) ( ((src[offset+3] & 0xFF)<<24)  
             |((src[offset+2] & 0xFF)<<16)  
             |((src[offset+1] & 0xFF)<<8)  
             |(src[offset+0] & 0xFF));  
      return value;  
   }  



   //byte[8]转long 大端序(低位在前,高位在后)
   public static long byte2Long(byte[] b) {  
         return  
         ((b[7]&0xff)<<56)|  
         ((b[6]&0xff)<<48)|  
         ((b[5]&0xff)<<40)|  
         ((b[4]&0xff)<<32)|  
         ((b[3]&0xff)<<24)|  
         ((b[2]&0xff)<<16)|  
         ((b[1]&0xff)<<8)|  
          (b[0]&0xff);  
    } 
    


     //byte[8]转long 大端序(低位在前,高位在后)
     public static long byte2Long(byte[] b, int offset) {  
         return ((((long) b[offset + 7] & 0xff) << 56)  
         | (((long) b[offset + 6] & 0xff) << 48)  
         | (((long) b[offset + 5] & 0xff) << 40)  
         | (((long) b[offset + 4] & 0xff) << 32)  
           
         | (((long) b[offset + 3] & 0xff) << 24)  
         | (((long) b[offset + 2] & 0xff) << 16)  
         | (((long) b[offset + 1] & 0xff) << 8)  
         | (((long) b[offset + 0] & 0xff) << 0));  
    }  




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值