`
saluya
  • 浏览: 120679 次
  • 性别: Icon_minigender_2
  • 来自: 西安
社区版块
存档分类
最新评论

整型数 和 网络字节序的 byte[] 数组之间的转换

 
阅读更多

public class ByteConvert {
    // 以下 是整型数 和 网络字节序的  byte[] 数组之间的转换
    public static byte[] longToBytes(long n) {
        byte[] b = new byte[8];
        b[7] = (byte) (n & 0xff);
        b[6] = (byte) (n >> 8  & 0xff);
        b[5] = (byte) (n >> 16 & 0xff);
        b[4] = (byte) (n >> 24 & 0xff);
        b[3] = (byte) (n >> 32 & 0xff);
        b[2] = (byte) (n >> 40 & 0xff);
        b[1] = (byte) (n >> 48 & 0xff);
        b[0] = (byte) (n >> 56 & 0xff);
        return b;
    }
    
    public static void longToBytes( long n, byte[] array, int offset ){
        array[7+offset] = (byte) (n & 0xff);
        array[6+offset] = (byte) (n >> 8 & 0xff);
        array[5+offset] = (byte) (n >> 16 & 0xff);
        array[4+offset] = (byte) (n >> 24 & 0xff);
        array[3+offset] = (byte) (n >> 32 & 0xff);
        array[2+offset] = (byte) (n >> 40 & 0xff);
        array[1+offset] = (byte) (n >> 48 & 0xff);
        array[0+offset] = (byte) (n >> 56 & 0xff);
    }
    
    public static long bytesToLong( byte[] array )
    {
        return ((((long) array[ 0] & 0xff) << 56)
              | (((long) array[ 1] & 0xff) << 48)
              | (((long) array[ 2] & 0xff) << 40)
              | (((long) array[ 3] & 0xff) << 32)
              | (((long) array[ 4] & 0xff) << 24)
              | (((long) array[ 5] & 0xff) << 16)
              | (((long) array[ 6] & 0xff) << 8) 
              | (((long) array[ 7] & 0xff) << 0));        
    }
    
    public static long bytesToLong( byte[] array, int offset )
    {
        return ((((long) array[offset + 0] & 0xff) << 56)
              | (((long) array[offset + 1] & 0xff) << 48)
              | (((long) array[offset + 2] & 0xff) << 40)
              | (((long) array[offset + 3] & 0xff) << 32)
              | (((long) array[offset + 4] & 0xff) << 24)
              | (((long) array[offset + 5] & 0xff) << 16)
              | (((long) array[offset + 6] & 0xff) << 8) 
              | (((long) array[offset + 7] & 0xff) << 0));            
    }
    
    public static byte[] intToBytes(int n) {
        byte[] b = new byte[4];
        b[3] = (byte) (n & 0xff);
        b[2] = (byte) (n >> 8 & 0xff);
        b[1] = (byte) (n >> 16 & 0xff);
        b[0] = (byte) (n >> 24 & 0xff);
        return b;
    }
    
    public static void intToBytes( int n, byte[] array, int offset ){
        array[3+offset] = (byte) (n & 0xff);
        array[2+offset] = (byte) (n >> 8 & 0xff);
        array[1+offset] = (byte) (n >> 16 & 0xff);
        array[offset] = (byte) (n >> 24 & 0xff);
    }    

    public static int bytesToInt(byte b[]) {
        return    b[3] & 0xff 
               | (b[2] & 0xff) << 8 
               | (b[1] & 0xff) << 16
               | (b[0] & 0xff) << 24;
    }

    public static int bytesToInt(byte b[], int offset) {
        return    b[offset+3] & 0xff 
               | (b[offset+2] & 0xff) << 8 
               | (b[offset+1] & 0xff) << 16
               | (b[offset] & 0xff) << 24;
    }

    public static byte[] uintToBytes( long n )
    {
        byte[] b = new byte[4];
        b[3] = (byte) (n & 0xff);
        b[2] = (byte) (n >> 8 & 0xff);
        b[1] = (byte) (n >> 16 & 0xff);
        b[0] = (byte) (n >> 24 & 0xff);
        
        return b;
    }

    public static void uintToBytes( long n, byte[] array, int offset ){
        array[3+offset] = (byte) (n );
        array[2+offset] = (byte) (n >> 8 & 0xff);
        array[1+offset] = (byte) (n >> 16 & 0xff);
        array[offset]   = (byte) (n >> 24 & 0xff);
    }

    public static long bytesToUint(byte[] array) {  
        return ((long) (array[3] & 0xff))  
             | ((long) (array[2] & 0xff)) << 8  
             | ((long) (array[1] & 0xff)) << 16  
             | ((long) (array[0] & 0xff)) << 24;  
    }

    public static long bytesToUint(byte[] array, int offset) {   
        return ((long) (array[offset+3] & 0xff))  
              | ((long) (array[offset+2] & 0xff)) << 8  
             | ((long) (array[offset+1] & 0xff)) << 16  
             | ((long) (array[offset]   & 0xff)) << 24;  
    }

    public static byte[] shortToBytes(short n) {
        byte[] b = new byte[2];
        b[1] = (byte) ( n       & 0xff);
        b[0] = (byte) ((n >> 8) & 0xff);
        return b;
    }
    
    public static void shortToBytes(short n, byte[] array, int offset ) {        
        array[offset+1] = (byte) ( n       & 0xff);
        array[offset] = (byte) ((n >> 8) & 0xff);
    }
    
    public static short bytesToShort(byte[] b){
        return (short)( b[1] & 0xff
                      |(b[0] & 0xff) << 8 ); 
    }    

    public static short bytesToShort(byte[] b, int offset){
        return (short)( b[offset+1] & 0xff
                      |(b[offset]    & 0xff) << 8 ); 
    }

    public static byte[] ushortToBytes(int n) {
        byte[] b = new byte[2];
        b[1] = (byte) ( n       & 0xff);
        b[0] = (byte) ((n >> 8) & 0xff);
        return b;
    }    

    public static void ushortToBytes(int n, byte[] array, int offset ) {
        array[offset+1] = (byte) ( n       & 0xff);
        array[offset] = (byte)   ((n >> 8) & 0xff);
    }

    public static int bytesToUshort(byte b[]) {
        return    b[1] & 0xff 
               | (b[0] & 0xff) << 8;
    }    

    public static int bytesToUshort(byte b[], int offset) {
        return    b[offset+1] & 0xff 
               | (b[offset]   & 0xff) << 8;
    }    

    public static byte[] ubyteToBytes( int n ){
        byte[] b = new byte[1];
        b[0] = (byte) (n & 0xff);
        return b;
    }

    public static void ubyteToBytes( int n, byte[] array, int offset ){
        array[0] = (byte) (n & 0xff);
    }

    public static int bytesToUbyte( byte[] array ){            
        return array[0] & 0xff;
    }        

    public static int bytesToUbyte( byte[] array, int offset ){            
        return array[offset] & 0xff;
    }    
    // char 类型、 float、double 类型和 byte[] 数组之间的转换关系还需继续研究实现。 
}

 
public class ByteConvertTest {
    
    public static String byte2Hex(byte[] buf) 
    {
        StringBuffer strbuf = new StringBuffer();
        strbuf.append("{");
        for (byte b : buf) 
        {
            if (b == 0) 
            {
                strbuf.append("00");
            } 
            else if (b == -1) 
            {
                strbuf.append("FF");
            } 
            else 
            {
                String str = Integer.toHexString(b).toUpperCase();
                // sb.append(a);
                if (str.length() == 8) 
                {
                    str = str.substring(6, 8);
                } 
                else if (str.length() < 2) 
                {
                    str = "0" + str;
                }
                strbuf.append(str);
            }
            strbuf.append(" ");
        }
        strbuf.append("}");
        return strbuf.toString();
    }    

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

    public static long bytesToLong( byte[] array )
    {
        return ((((long) array[ 0] & 0xff) << 56)
              | (((long) array[ 1] & 0xff) << 48)
              | (((long) array[ 2] & 0xff) << 40)
              | (((long) array[ 3] & 0xff) << 32)
              | (((long) array[ 4] & 0xff) << 24)
              | (((long) array[ 5] & 0xff) << 16)
              | (((long) array[ 6] & 0xff) << 8) 
              | (((long) array[ 7] & 0xff) ));        
    }
    
    public static int bytesToInt(byte b[]) {
        return    b[3] & 0xff 
               | (b[2] & 0xff) << 8 
               | (b[1] & 0xff) << 16
               | (b[0] & 0xff) << 24;
    }

    public static long bytesToUint(byte[] array) {  
        return ((long) (array[3] & 0xff))  
             | ((long) (array[2] & 0xff)) << 8  
             | ((long) (array[1] & 0xff)) << 16  
             | ((long) (array[0] & 0xff)) << 24;  
    }

    public static byte[] uintToBytes( long n )
    {
        byte[] b = new byte[4];
        b[3] = (byte) (n & 0xff);
        b[2] = (byte) (n >> 8 & 0xff);
        b[1] = (byte) (n >> 16 & 0xff);
        b[0] = (byte) (n >> 24 & 0xff);
        
        return b;
    }
    

    public static byte[] shortToBytes(short n) {
        byte[] b = new byte[2];
        b[1] = (byte) ( n       & 0xff);
        b[0] = (byte) ((n >> 8) & 0xff);
        return b;
    }
    
    public static short bytesToShort(byte[] b){
        return (short)( b[1] & 0xff
                      |(b[0] & 0xff) << 8 ); 
    }
    
    static void testShortConvert(){
        System.out.println("=================== short convert =============");
        System.out.println("byte2Hex(shortToBytes((short)0x11f2))"+byte2Hex(shortToBytes((short)0x11f2)));        
        System.out.print("println 0x11f2:");
        System.out.println((short)0x11f2);        
        System.out.println("byte2Hex(shortToBytes((short)0xf1f2))"+byte2Hex(shortToBytes((short)0xf1f2)));        
        System.out.print("println 0xf1f2:");
        System.out.println((short)0xf1f2);            
        System.out.print("println bytesToShort(shortToBytes((short)0x11f2)):");
        System.out.println((short)bytesToShort(shortToBytes((short)0x11f2)));            
        System.out.print("println bytesToShort(shortToBytes((short)0xf1f2)):");
        System.out.println((short)bytesToShort(shortToBytes((short)0xf1f2)));        
    }
    

    public static byte[] ushortToBytes(int n) {
        byte[] b = new byte[2];
        b[1] = (byte) (n & 0xff);
        b[0] = (byte) (n >> 8 & 0xff);
        return b;
    }
    

    public static int bytesToUshort(byte b[]) {
        return    b[1] & 0xff 
               | (b[0] & 0xff) << 8;
    }

    static void testUshortConvert(){
        System.out.println("=================== Ushort convert =============");
        System.out.println("byte2Hex(ushortToBytes(0x11f2))"+byte2Hex(ushortToBytes(0x11f2)));        
        System.out.print("println 0x11f2:");
        System.out.println(0x11f2);        
        System.out.println("byte2Hex(ushortToBytes(0xf1f2))"+byte2Hex(ushortToBytes(0xf1f2)));        
        System.out.print("println 0xf1f2:");
        System.out.println(0xf1f2);            
        System.out.print("println bytesToUshort(ushortToBytes(0x11f2)):");
        System.out.println(bytesToUshort(ushortToBytes(0x11f2)));            
        System.out.print("println bytesToUshort(ushortToBytes(0xf1f2)):");
        System.out.println(bytesToUshort(ushortToBytes(0xf1f2)));        
    }
    
    public static byte[] ubyteToBytes( int n ){
        byte[] b = new byte[1];
        b[0] = (byte) (n & 0xff);
        return b;
    }

    public static int bytesToUbyte( byte[] array ){            
        return array[0] & 0xff;
    }    

    static void testUbyteConvert(){
        System.out.println("=================== Ubyte convert =============");
        System.out.println("byte2Hex(ubyteToBytes(0x1112))"+byte2Hex(ubyteToBytes(0x1112)));        
        System.out.print("println 0x1112:");
        System.out.println(0x1112);        
        System.out.println("byte2Hex(ubyteToBytes(0xf2))"+byte2Hex(ubyteToBytes(0xf2)));        
        System.out.print("println 0xf2:");
        System.out.println(0xf2);            
        System.out.print("println bytesToUbyte(ubyteToBytes(0x1112)):");
        System.out.println(bytesToUbyte(ubyteToBytes(0x1112)));            
        System.out.print("println bytesToUbyte(ubyteToBytes(0xf1f2)):");
        System.out.println(bytesToUbyte(ubyteToBytes(0xf1f2)));        
    }
    
    
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub        
        byte[] array = new byte[4];
        array[3] = (byte) 0xF4;
        array[2] = 0x13;
        array[1] = 0x12;
        array[0] = 0x11;
        
        System.out.println("=================== Integer bytes =============");
        
        System.out.println("the bytes is:"+byte2Hex(array) );
        System.out.print("println bytesToInt :");
        System.out.println( bytesToInt(array));
        System.out.printf("printf bytesToInt :%X\n", bytesToInt(array));
        
        System.out.println("=================== long bytes =============");
        byte[] longBytes = new byte[8];
        
        longBytes[7] = (byte) 0xf7;
        longBytes[6] = (byte) 0x16;
        longBytes[5] = (byte) 0xf5;
        longBytes[4] = (byte) 0x14;
        longBytes[3] = (byte) 0xf3;
        longBytes[2] = (byte) 0x12;
        longBytes[1] = (byte) 0xf1;
        longBytes[0] = (byte) 0x10;
        

        System.out.println( "the bytes is:"+byte2Hex(longBytes) );
        System.out.printf("printf bytesToLong:%X\n",bytesToLong(longBytes));
        
        System.out.println("=================byte to long ================");
        
        byte b = (byte)0xf1;
        System.out.print("Println the byte:");
        System.out.println(b);
        System.out.printf("Printf the byte:%X\n",b);
        long l = b;
        System.out.print("Println byte to long:");
        System.out.println(l);
        System.out.printf("printf byte to long:%X\n",l);
        
        System.out.println("================= uint Bytes ================");
        
        byte[] uint = new byte[4];
        uint[3] = (byte) 0xf3;
        uint[2] = (byte) 0x12;
        uint[1] = (byte) 0xf1;
        uint[0] = (byte) 0xFF;
        
        System.out.println( "the bytes is:"+byte2Hex(uint) );
        System.out.printf("printf bytesToUint:%X\n",bytesToUint(uint));
        System.out.print("Println bytesToUint:");
        System.out.println(bytesToUint(uint));
        System.out.println("byte2Hex(uintToBytes(0x11f2f3f4f5f6f7f8l)):"+byte2Hex(uintToBytes(0x11f2f3f4f5f6f7f8l)));
        
        System.out.println("===============Long Integer==============");        
        System.out.print("println 0x11f2f3f4f5f6f7f8l:");
        System.out.println(0x11f2f3f4f5f6f7f8l);        
        System.out.printf("Printf 0x11f2f3f4f5f6f7f8l:%X\n",0x11f2f3f4f5f6f7f8l);
        System.out.println("println byte2Hex(longToBytes(0x11f2f3f4f5f6f7f8l))"+byte2Hex(longToBytes(0x11f2f3f4f5f6f7f8l)));
        // 注意,下面的这行,并不能获得正确的uint。
        System.out.printf("printf bytesToUint(longToBytes(0x11f2f3f4f5f6f7f8l):%X\n",bytesToUint(longToBytes(0x11f2f3f4f5f6f7f8l)));
        
        System.out.println("===============bytesToLong(longToBytes())==============");
        System.out.println(bytesToLong(longToBytes(0x11f2f3f4f5f6f7f8l)));
        System.out.printf("%X\n",bytesToLong(longToBytes(0x11f2f3f4f5f6f7f8l)));
        
        testShortConvert();
        testUshortConvert();
        testUbyteConvert();
    }

}
 
分享到:
评论

相关推荐

    Java整型数与网络字节序byte[]数组转换关系详解

    "Java整型数与网络字节序byte[]数组转换关系详解" 本文主要介绍了Java整型数与网络字节序byte[]数组之间的转换关系,包括整型数到byte[]数组的转换和byte[]数组到整型数的转换。这些转换关系在Java和C/C++之间的...

    int类型和byte数组之间的转换

    写一个方法,将int类型转换为字节数组,输入任意int类型整型,输出字节数组;写第二个方法,输入字节数组,输出对应int类型数据。

    java数据类型转byte数组

    ip地址转4字节byte,char转2字节byte,byte数组转char,int整数转换为4字节的byte数组,byte数组转换为int整数,double类型转8字节数组,8位数组转double,long整数转换为8字节的byte数组,short整数转换为2字节的...

    C# Byte数组转Int32 Short Float(浮点数)

    标题和描述提到的“C# Byte数组转Int32 Short Float(浮点数)”是指将字节数组中的数据转换为整型(Int32)、短整型(Short)以及浮点数(Float)的过程。以下是对这个主题的详细解释: **字节数组基础** 字节数组...

    C#结构体和C++字节数组的转换

    反向操作,即从字节数组转换回结构体,可以这样实现: ```csharp public static object BytesToStruct(byte[] bytes, Type type) { int size = Marshal.SizeOf(type); if (size &gt; bytes.Length) return null; ...

    java基本类型与byte数组互相转换

    Byte数组转换为Short值 最后,`byte`数组也可以转换回相应的基本类型。例如,将2字节的`byte`数组转换为`short`值: ```java public static short byteArrToShort(byte[] b) { byte[] a = new byte[2]; int i =...

    C#中结构体struct和字节数组Byte的之间的转换函数

    在C#编程语言中,当涉及到TCP通信时,由于TCP通信本质上是基于字节流的,因此在处理自定义的数据结构如结构体(struct)时,通常需要将这些结构体转换为字节数组(byte[])进行传输,之后再在接收端还原成原来的...

    LabVIEW,字节数组至数值转换

    LabVIEW程序,功能:将4字节的unsigned char输入组合成1个32-bit int值,若输入字节数不等于4则报错。

    Java基本类型与byte数组之间相互转换方法

    总之,这些方法提供了在Java中基础数据类型和byte数组之间转换的实用工具。它们对于数据的序列化和反序列化,网络传输,或者任何需要将数据转换为字节流的场景都非常有用。需要注意的是,进行这样的转换时,必须考虑...

    java基本类型与byte数组互相转换.rar

    此外,Java的`DataInputStream`和`DataOutputStream`也可以用来进行基本类型与字节流之间的转换,它们提供了如`readInt()`, `writeInt()`, `readFloat()`, `writeFloat()`等方法。 在实际应用中,需要注意字节顺序...

    java byte相互转换详解左右位移

    相反,从byte数组转换回int类型则需要将这些字节合并起来。 **转换方法:** 1. **byte转int**:将一个byte转换为int,可以通过与0xFF进行按位与操作(AND),然后根据位移规则进行左移或右移操作。例如,`byte b =...

    数组的转换函数

    上述代码片段提供了一些在Java中实现整型数(long类型)与网络字节序的字节数组之间转换的方法。以下是这些方法的详细说明: 1. `longToBytes(long n)`:这个静态方法将一个长整型(long)数值`n`转换为一个8字节的...

    字节和float转换小工具

    标题中的"字节和float转换小工具"是一个专门针对字节与浮点数(float)之间转换的实用程序。这个小工具设计的目标是帮助开发者高效地在字节序列和浮点数之间进行切换,这在数据传输、存储或解析二进制文件时非常有用...

    TIA博途-字节Byte转换成双字Dword全局FC库文件-V17版本-GF-Byte-To-Dword.zip

    在本资源中,我们关注的是一个特定的函数库,用于实现字节(Byte)到双字(Dword)的数据转换。 字节(Byte)是计算机存储和处理数据的基本单位,通常一个字节包含8位(bit)。在西门子的S7系列PLC中,字节常用于...

    将字节数组转换为各种基本类型

    标题提到的“将字节数组转换为各种基本类型”涉及到的是字节数组与C#的基本数据类型之间的转换,如整型(int)、浮点型(float)、双精度型(double)等。下面将详细介绍这一主题,以及如何在C#中进行这些转换。 1....

    BIT_BYTE.zip_数组转换

    本示例"BIT_BYTE.zip_数组转换"着重探讨了如何在程序中实现整型(int)数组与字符(char)数组之间的转换。这种转换在处理二进制数据、字符串编码、以及与硬件交互等场景中十分常见。 一、整型数组到字符数组的转换 1....

    labview 4字节一维数组整数转为4字节16进制字符串.vi

    labview 读取的一维数组(整数)转换成16进制的字符串,方便大家进行数据处理。有问题可以留言咨询,互相学习

    C#中二进制数组转换,二进制序列化和json序列化方法

    反向转换,即将二进制数组转换回整型数组,同样可以使用BitConverter,但需要考虑字节顺序(小端或大端): ```csharp byteArray = ... // 已有的二进制数组 intArray = new int[byteArray.Length / sizeof(int)]; ...

    十六进制转字节工具

    在C语言编程中,处理字节(Byte)是常见的任务,因为字节是计算机存储和传输数据的基本单位,通常由8位二进制数组成。"十六进制转字节工具"就是为了解决这种需求,帮助开发者将十六进制数值转换为字节形式,便于在...

    Java byte数组操纵方式代码实例解析

    - 字节数组与整型(int)、长整型(long)、短整型(short)和字节类型(byte)之间的转换,需要根据字节顺序和位运算进行操作。 - 字符串与字节数组的相互转换,Java的`getBytes()`和`new String(byte[])`方法是...

Global site tag (gtag.js) - Google Analytics