`
sdutdazzling
  • 浏览: 31398 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

Java字节序,java整型数与网络字节序 byte[] 数组转换关系(ByteArrayOutputStream用法)

 
阅读更多

[java] view plaincopy
  1. /** 
  2. * 通信格式转换 
  3. * 
  4. * Java和一些windows编程语言如c、c++、delphi所写的网络程序进行通讯时,需要进行相应的转换 
  5. * 高、低字节之间的转换 
  6. * windows的字节序为低字节开头 
  7. * linux,unix的字节序为高字节开头 
  8. * java则无论平台变化,都是高字节开头 
  9.   */   
  10.   
  11. public class FormatTransfer {  
  12. /** 
  13.   * 将int转为低字节在前,高字节在后的byte数组 
  14.   * @param n int 
  15.   * @return byte[] 
  16.   */  
  17. public static byte[] toLH(int n) {  
  18.   byte[] b = new byte[4];  
  19.   b[0] = (byte) (n & 0xff);  
  20.   b[1] = (byte) (n >> 8 & 0xff);  
  21.   b[2] = (byte) (n >> 16 & 0xff);  
  22.   b[3] = (byte) (n >> 24 & 0xff);  
  23.   return b;  
  24. }   
  25.   
  26. /** 
  27.   * 将int转为高字节在前,低字节在后的byte数组 
  28.   * @param n int 
  29.   * @return byte[] 
  30.   */  
  31. public static byte[] toHH(int n) {  
  32.   byte[] b = new byte[4];  
  33.   b[3] = (byte) (n & 0xff);  
  34.   b[2] = (byte) (n >> 8 & 0xff);  
  35.   b[1] = (byte) (n >> 16 & 0xff);  
  36.   b[0] = (byte) (n >> 24 & 0xff);  
  37.   return b;  
  38. }   
  39.   
  40. /** 
  41.   * 将short转为低字节在前,高字节在后的byte数组 
  42.   * @param n short 
  43.   * @return byte[] 
  44.   */  
  45. public static byte[] toLH(short n) {  
  46.   byte[] b = new byte[2];  
  47.   b[0] = (byte) (n & 0xff);  
  48.   b[1] = (byte) (n >> 8 & 0xff);  
  49.   return b;  
  50. }   
  51.   
  52. /** 
  53.   * 将short转为高字节在前,低字节在后的byte数组 
  54.   * @param n short 
  55.   * @return byte[] 
  56.   */  
  57. public static byte[] toHH(short n) {  
  58.   byte[] b = new byte[2];  
  59.   b[1] = (byte) (n & 0xff);  
  60.   b[0] = (byte) (n >> 8 & 0xff);  
  61.   return b;  
  62. }   
  63.   
  64.   
  65.   
  66. /** 
  67.   * 将将int转为高字节在前,低字节在后的byte数组  
  68.  
  69. public static byte[] toHH(int number) { 
  70.   int temp = number; 
  71.   byte[] b = new byte[4]; 
  72.   for (int i = b.length - 1; i > -1; i--) { 
  73.     b = new Integer(temp & 0xff).byteValue(); 
  74.     temp = temp >> 8; 
  75.   } 
  76.   return b; 
  77.  
  78.  
  79. public static byte[] IntToByteArray(int i) { 
  80.     byte[] abyte0 = new byte[4]; 
  81.     abyte0[3] = (byte) (0xff & i); 
  82.     abyte0[2] = (byte) ((0xff00 & i) >> 8); 
  83.     abyte0[1] = (byte) ((0xff0000 & i) >> 16); 
  84.     abyte0[0] = (byte) ((0xff000000 & i) >> 24); 
  85.     return abyte0; 
  86.  
  87.  
  88.  
  89. */   
  90.   
  91. /** 
  92.   * 将float转为低字节在前,高字节在后的byte数组 
  93.   */  
  94. public static byte[] toLH(float f) {  
  95.   return toLH(Float.floatToRawIntBits(f));  
  96. }   
  97.   
  98. /** 
  99.   * 将float转为高字节在前,低字节在后的byte数组 
  100.   */  
  101. public static byte[] toHH(float f) {  
  102.   return toHH(Float.floatToRawIntBits(f));  
  103. }   
  104.   
  105. /** 
  106.   * 将String转为byte数组 
  107.   */  
  108. public static byte[] stringToBytes(String s, int length) {  
  109.   while (s.getBytes().length < length) {  
  110.     s += " ";  
  111.   }  
  112.   return s.getBytes();  
  113. }   
  114.   
  115.   
  116. /** 
  117.   * 将字节数组转换为String 
  118.   * @param b byte[] 
  119.   * @return String 
  120.   */  
  121. public static String bytesToString(byte[] b) {  
  122.   StringBuffer result = new StringBuffer("");  
  123.   int length = b.length;  
  124.   for (int i=0; i<length; i++) {  
  125.     result.append((char)(b & 0xff));  
  126.   }  
  127.   return result.toString();  
  128. }   
  129.   
  130. /** 
  131.   * 将字符串转换为byte数组 
  132.   * @param s String 
  133.   * @return byte[] 
  134.   */  
  135. public static byte[] stringToBytes(String s) {  
  136.   return s.getBytes();  
  137. }   
  138.   
  139. /** 
  140.   * 将高字节数组转换为int 
  141.   * @param b byte[] 
  142.   * @return int 
  143.   */  
  144. public static int hBytesToInt(byte[] b) {  
  145.   int s = 0;  
  146.   for (int i = 0; i < 3; i++) {  
  147.     if (b >= 0) {  
  148.     s = s + b;  
  149.     } else {  
  150.     s = s + 256 + b;  
  151.     }  
  152.     s = s * 256;  
  153.   }  
  154.   if (b[3] >= 0) {  
  155.     s = s + b[3];  
  156.   } else {  
  157.     s = s + 256 + b[3];  
  158.   }  
  159.   return s;  
  160. }   
  161.   
  162. /** 
  163.   * 将低字节数组转换为int 
  164.   * @param b byte[] 
  165.   * @return int 
  166.   */  
  167. public static int lBytesToInt(byte[] b) {  
  168.   int s = 0;  
  169.   for (int i = 0; i < 3; i++) {  
  170.     if (b[3-i] >= 0) {  
  171.     s = s + b[3-i];  
  172.     } else {  
  173.     s = s + 256 + b[3-i];  
  174.     }  
  175.     s = s * 256;  
  176.   }  
  177.   if (b[0] >= 0) {  
  178.     s = s + b[0];  
  179.   } else {  
  180.     s = s + 256 + b[0];  
  181.   }  
  182.   return s;  
  183. }   
  184.   
  185.   
  186. /** 
  187.   * 高字节数组到short的转换 
  188.   * @param b byte[] 
  189.   * @return short 
  190.   */  
  191. public static short hBytesToShort(byte[] b) {  
  192.   int s = 0;  
  193.   if (b[0] >= 0) {  
  194.     s = s + b[0];  
  195.     } else {  
  196.     s = s + 256 + b[0];  
  197.     }  
  198.     s = s * 256;  
  199.   if (b[1] >= 0) {  
  200.     s = s + b[1];  
  201.   } else {  
  202.     s = s + 256 + b[1];  
  203.   }  
  204.   short result = (short)s;  
  205.   return result;  
  206. }   
  207.   
  208. /** 
  209.   * 低字节数组到short的转换 
  210.   * @param b byte[] 
  211.   * @return short 
  212.   */  
  213. public static short lBytesToShort(byte[] b) {  
  214.   int s = 0;  
  215.   if (b[1] >= 0) {  
  216.     s = s + b[1];  
  217.     } else {  
  218.     s = s + 256 + b[1];  
  219.     }  
  220.     s = s * 256;  
  221.   if (b[0] >= 0) {  
  222.     s = s + b[0];  
  223.   } else {  
  224.     s = s + 256 + b[0];  
  225.   }  
  226.   short result = (short)s;  
  227.   return result;  
  228. }   
  229.   
  230. /** 
  231.   * 高字节数组转换为float 
  232.   * @param b byte[] 
  233.   * @return float 
  234.   */  
  235. public static float hBytesToFloat(byte[] b) {  
  236.   int i = 0;  
  237.   Float F = new Float(0.0);  
  238.   i = ((((b[0]&0xff)<<8 | (b[1]&0xff))<<8) | (b[2]&0xff))<<8 | (b[3]&0xff);  
  239.   return F.intBitsToFloat(i);  
  240. }   
  241.   
  242. /** 
  243.   * 低字节数组转换为float 
  244.   * @param b byte[] 
  245.   * @return float 
  246.   */  
  247. public static float lBytesToFloat(byte[] b) {  
  248.   int i = 0;  
  249.   Float F = new Float(0.0);  
  250.   i = ((((b[3]&0xff)<<8 | (b[2]&0xff))<<8) | (b[1]&0xff))<<8 | (b[0]&0xff);  
  251.   return F.intBitsToFloat(i);  
  252. }   
  253.   
  254. /** 
  255.   * 将byte数组中的元素倒序排列 
  256.   */  
  257. public static byte[] bytesReverseOrder(byte[] b) {  
  258.   int length = b.length;  
  259.   byte[] result = new byte[length];  
  260.   for(int i=0; i<length; i++) {  
  261.     result[length-i-1] = b;  
  262.   }  
  263.   return result;  
  264. }   
  265.   
  266. /** 
  267.   * 打印byte数组 
  268.   */  
  269. public static void printBytes(byte[] bb) {  
  270.   int length = bb.length;  
  271.   for (int i=0; i<length; i++) {  
  272.     System.out.print(bb + " ");  
  273.   }  
  274.   System.out.println("");  
  275. }   
  276.   
  277. public static void logBytes(byte[] bb) {  
  278.   int length = bb.length;  
  279.   String out = "";  
  280.   for (int i=0; i<length; i++) {  
  281.     out = out + bb + " ";  
  282.   }   
  283.   
  284. }   
  285.   
  286. /** 
  287.   * 将int类型的值转换为字节序颠倒过来对应的int值 
  288.   * @param i int 
  289.   * @return int 
  290.   */  
  291. public static int reverseInt(int i) {  
  292.   int result = FormatTransfer.hBytesToInt(FormatTransfer.toLH(i));  
  293.   return result;  
  294. }   
  295.   
  296. /** 
  297.   * 将short类型的值转换为字节序颠倒过来对应的short值 
  298.   * @param s short 
  299.   * @return short 
  300.   */  
  301. public static short reverseShort(short s) {  
  302.   short result = FormatTransfer.hBytesToShort(FormatTransfer.toLH(s));  
  303.   return result;  
  304. }   
  305.   
  306. /** 
  307.   * 将float类型的值转换为字节序颠倒过来对应的float值 
  308.   * @param f float 
  309.   * @return float 
  310.   */  
  311. public static float reverseFloat(float f) {  
  312.   float result = FormatTransfer.hBytesToFloat(FormatTransfer.toLH(f));  
  313.   return result;  
  314. }   
  315.   
  316. }  

 

java整型数与网络字节序的 byte[] 数组转换关系

http://www.cnblogs.com/devinzhang/archive/2012/09/28/2707605.html

工作项目需要在java和c/c++之间进行socket通信,socket通信是以字节流或者字节包进行的,socket发送方须将数据转换为字节流或者字节包,而接收方则将字节流和字节包再转换回相应的数据类型。如果发送方和接收方都是同种语言,则一般只涉及到字节序的调整。而对于java和c/c++的通信,则情况就要复杂一些,主要是因为java中没有unsigned类型,并且java和c在某些数据类型上的长度不一致。
  本文就是针对这种情况,整理了java数据类型和网络字节流或字节包(相当于java的byte数组)之间转换方法。实际上网上这方面的资料不少,但往往不全,甚至有些有错误,于是就花了点时间对java整型数和网络字节序的byte[]之间转换的各种情况做了一些验证和整理。整理出来的函数如下:

[java] view plaincopy
  1. public class ByteConvert {  
  2.     // 以下 是整型数 和 网络字节序的  byte[] 数组之间的转换  
  3.     public static byte[] longToBytes(long n) {  
  4.         byte[] b = new byte[8];  
  5.         b[7] = (byte) (n & 0xff);  
  6.         b[6] = (byte) (n >> 8  & 0xff);  
  7.         b[5] = (byte) (n >> 16 & 0xff);  
  8.         b[4] = (byte) (n >> 24 & 0xff);  
  9.         b[3] = (byte) (n >> 32 & 0xff);  
  10.         b[2] = (byte) (n >> 40 & 0xff);  
  11.         b[1] = (byte) (n >> 48 & 0xff);  
  12.         b[0] = (byte) (n >> 56 & 0xff);  
  13.         return b;  
  14.     }  
  15.       
  16.     public static void longToBytes( long n, byte[] array, int offset ){  
  17.         array[7+offset] = (byte) (n & 0xff);  
  18.         array[6+offset] = (byte) (n >> 8 & 0xff);  
  19.         array[5+offset] = (byte) (n >> 16 & 0xff);  
  20.         array[4+offset] = (byte) (n >> 24 & 0xff);  
  21.         array[3+offset] = (byte) (n >> 32 & 0xff);  
  22.         array[2+offset] = (byte) (n >> 40 & 0xff);  
  23.         array[1+offset] = (byte) (n >> 48 & 0xff);  
  24.         array[0+offset] = (byte) (n >> 56 & 0xff);  
  25.     }  
  26.       
  27.     public static long bytesToLong( byte[] array )  
  28.     {  
  29.         return ((((long) array[ 0] & 0xff) << 56)  
  30.               | (((long) array[ 1] & 0xff) << 48)  
  31.               | (((long) array[ 2] & 0xff) << 40)  
  32.               | (((long) array[ 3] & 0xff) << 32)  
  33.               | (((long) array[ 4] & 0xff) << 24)  
  34.               | (((long) array[ 5] & 0xff) << 16)  
  35.               | (((long) array[ 6] & 0xff) << 8)   
  36.               | (((long) array[ 7] & 0xff) << 0));          
  37.     }  
  38.       
  39.     public static long bytesToLong( byte[] array, int offset )  
  40.     {  
  41.         return ((((long) array[offset + 0] & 0xff) << 56)  
  42.               | (((long) array[offset + 1] & 0xff) << 48)  
  43.               | (((long) array[offset + 2] & 0xff) << 40)  
  44.               | (((long) array[offset + 3] & 0xff) << 32)  
  45.               | (((long) array[offset + 4] & 0xff) << 24)  
  46.               | (((long) array[offset + 5] & 0xff) << 16)  
  47.               | (((long) array[offset + 6] & 0xff) << 8)   
  48.               | (((long) array[offset + 7] & 0xff) << 0));              
  49.     }  
  50.       
  51.     public static byte[] intToBytes(int n) {  
  52.         byte[] b = new byte[4];  
  53.         b[3] = (byte) (n & 0xff);  
  54.         b[2] = (byte) (n >> 8 & 0xff);  
  55.         b[1] = (byte) (n >> 16 & 0xff);  
  56.         b[0] = (byte) (n >> 24 & 0xff);  
  57.         return b;  
  58.     }  
  59.       
  60.     public static void intToBytes( int n, byte[] array, int offset ){  
  61.         array[3+offset] = (byte) (n & 0xff);  
  62.         array[2+offset] = (byte) (n >> 8 & 0xff);  
  63.         array[1+offset] = (byte) (n >> 16 & 0xff);  
  64.         array[offset] = (byte) (n >> 24 & 0xff);  
  65.     }      
  66.   
  67.     public static int bytesToInt(byte b[]) {  
  68.         return    b[3] & 0xff   
  69.                | (b[2] & 0xff) << 8   
  70.                | (b[1] & 0xff) << 16  
  71.                | (b[0] & 0xff) << 24;  
  72.     }  
  73.   
  74.     public static int bytesToInt(byte b[], int offset) {  
  75.         return    b[offset+3] & 0xff   
  76.                | (b[offset+2] & 0xff) << 8   
  77.                | (b[offset+1] & 0xff) << 16  
  78.                | (b[offset] & 0xff) << 24;  
  79.     }  
  80.   
  81.     public static byte[] uintToBytes( long n )  
  82.     {  
  83.         byte[] b = new byte[4];  
  84.         b[3] = (byte) (n & 0xff);  
  85.         b[2] = (byte) (n >> 8 & 0xff);  
  86.         b[1] = (byte) (n >> 16 & 0xff);  
  87.         b[0] = (byte) (n >> 24 & 0xff);  
  88.           
  89.         return b;  
  90.     }  
  91.   
  92.     public static void uintToBytes( long n, byte[] array, int offset ){  
  93.         array[3+offset] = (byte) (n );  
  94.         array[2+offset] = (byte) (n >> 8 & 0xff);  
  95.         array[1+offset] = (byte) (n >> 16 & 0xff);  
  96.         array[offset]   = (byte) (n >> 24 & 0xff);  
  97.     }  
  98.   
  99.     public static long bytesToUint(byte[] array) {    
  100.         return ((long) (array[3] & 0xff))    
  101.              | ((long) (array[2] & 0xff)) << 8    
  102.              | ((long) (array[1] & 0xff)) << 16    
  103.              | ((long) (array[0] & 0xff)) << 24;    
  104.     }  
  105.   
  106.     public static long bytesToUint(byte[] array, int offset) {     
  107.         return ((long) (array[offset+3] & 0xff))    
  108.               | ((long) (array[offset+2] & 0xff)) << 8    
  109.              | ((long) (array[offset+1] & 0xff)) << 16    
  110.              | ((long) (array[offset]   & 0xff)) << 24;    
  111.     }  
  112.   
  113.     public static byte[] shortToBytes(short n) {  
  114.         byte[] b = new byte[2];  
  115.         b[1] = (byte) ( n       & 0xff);  
  116.         b[0] = (byte) ((n >> 8) & 0xff);  
  117.         return b;  
  118.     }  
  119.       
  120.     public static void shortToBytes(short n, byte[] array, int offset ) {          
  121.         array[offset+1] = (byte) ( n       & 0xff);  
  122.         array[offset] = (byte) ((n >> 8) & 0xff);  
  123.     }  
  124.       
  125.     public static short bytesToShort(byte[] b){  
  126.         return (short)( b[1] & 0xff  
  127.                       |(b[0] & 0xff) << 8 );   
  128.     }      
  129.   
  130.     public static short bytesToShort(byte[] b, int offset){  
  131.         return (short)( b[offset+1] & 0xff  
  132.                       |(b[offset]    & 0xff) << 8 );   
  133.     }  
  134.   
  135.     public static byte[] ushortToBytes(int n) {  
  136.         byte[] b = new byte[2];  
  137.         b[1] = (byte) ( n       & 0xff);  
  138.         b[0] = (byte) ((n >> 8) & 0xff);  
  139.         return b;  
  140.     }      
  141.   
  142.     public static void ushortToBytes(int n, byte[] array, int offset ) {  
  143.         array[offset+1] = (byte) ( n       & 0xff);  
  144.         array[offset] = (byte)   ((n >> 8) & 0xff);  
  145.     }  
  146.   
  147.     public static int bytesToUshort(byte b[]) {  
  148.         return    b[1] & 0xff   
  149.                | (b[0] & 0xff) << 8;  
  150.     }      
  151.   
  152.     public static int bytesToUshort(byte b[], int offset) {  
  153.         return    b[offset+1] & 0xff   
  154.                | (b[offset]   & 0xff) << 8;  
  155.     }      
  156.   
  157.     public static byte[] ubyteToBytes( int n ){  
  158.         byte[] b = new byte[1];  
  159.         b[0] = (byte) (n & 0xff);  
  160.         return b;  
  161.     }  
  162.   
  163.     public static void ubyteToBytes( int n, byte[] array, int offset ){  
  164.         array[0] = (byte) (n & 0xff);  
  165.     }  
  166.   
  167.     public static int bytesToUbyte( byte[] array ){              
  168.         return array[0] & 0xff;  
  169.     }          
  170.   
  171.     public static int bytesToUbyte( byte[] array, int offset ){              
  172.         return array[offset] & 0xff;  
  173.     }      
  174.     // char 类型、 float、double 类型和 byte[] 数组之间的转换关系还需继续研究实现。   
  175. }  
  176.   
  177.   
  178. 测试程序如下:  
  179.   
  180. public class ByteConvertTest {  
  181.       
  182.     public static String byte2Hex(byte[] buf)   
  183.     {  
  184.         StringBuffer strbuf = new StringBuffer();  
  185.         strbuf.append("{");  
  186.         for (byte b : buf)   
  187.         {  
  188.             if (b == 0)   
  189.             {  
  190.                 strbuf.append("00");  
  191.             }   
  192.             else if (b == -1)   
  193.             {  
  194.                 strbuf.append("FF");  
  195.             }   
  196.             else   
  197.             {  
  198.                 String str = Integer.toHexString(b).toUpperCase();  
  199.                 // sb.append(a);  
  200.                 if (str.length() == 8)   
  201.                 {  
  202.                     str = str.substring(68);  
  203.                 }   
  204.                 else if (str.length() < 2)   
  205.                 {  
  206.                     str = "0" + str;  
  207.                 }  
  208.                 strbuf.append(str);  
  209.             }  
  210.             strbuf.append(" ");  
  211.         }  
  212.         strbuf.append("}");  
  213.         return strbuf.toString();  
  214.     }      
  215.   
  216.     public static byte[] longToBytes(long n) {  
  217.         byte[] b = new byte[8];  
  218.         b[7] = (byte) (n & 0xff);  
  219.         b[6] = (byte) (n >> 8  & 0xff);  
  220.         b[5] = (byte) (n >> 16 & 0xff);  
  221.         b[4] = (byte) (n >> 24 & 0xff);  
  222.         b[3] = (byte) (n >> 32 & 0xff);  
  223.         b[2] = (byte) (n >> 40 & 0xff);  
  224.         b[1] = (byte) (n >> 48 & 0xff);  
  225.         b[0] = (byte) (n >> 56 & 0xff);  
  226.         return b;  
  227.     }  
  228.   
  229.     public static long bytesToLong( byte[] array )  
  230.     {  
  231.         return ((((long) array[ 0] & 0xff) << 56)  
  232.               | (((long) array[ 1] & 0xff) << 48)  
  233.               | (((long) array[ 2] & 0xff) << 40)  
  234.               | (((long) array[ 3] & 0xff) << 32)  
  235.               | (((long) array[ 4] & 0xff) << 24)  
  236.               | (((long) array[ 5] & 0xff) << 16)  
  237.               | (((long) array[ 6] & 0xff) << 8)   
  238.               | (((long) array[ 7] & 0xff) ));          
  239.     }  
  240.       
  241.     public static int bytesToInt(byte b[]) {  
  242.         return    b[3] & 0xff   
  243.                | (b[2] & 0xff) << 8   
  244.                | (b[1] & 0xff) << 16  
  245.                | (b[0] & 0xff) << 24;  
  246.     }  
  247.   
  248.     public static long bytesToUint(byte[] array) {    
  249.         return ((long) (array[3] & 0xff))    
  250.              | ((long) (array[2] & 0xff)) << 8    
  251.              | ((long) (array[1] & 0xff)) << 16    
  252.              | ((long) (array[0] & 0xff)) << 24;    
  253.     }  
  254.   
  255.     public static byte[] uintToBytes( long n )  
  256.     {  
  257.         byte[] b = new byte[4];  
  258.         b[3] = (byte) (n & 0xff);  
  259.         b[2] = (byte) (n >> 8 & 0xff);  
  260.         b[1] = (byte) (n >> 16 & 0xff);  
  261.         b[0] = (byte) (n >> 24 & 0xff);  
  262.           
  263.         return b;  
  264.     }  
  265.       
  266.   
  267.     public static byte[] shortToBytes(short n) {  
  268.         byte[] b = new byte[2];  
  269.         b[1] = (byte) ( n       & 0xff);  
  270.         b[0] = (byte) ((n >> 8) & 0xff);  
  271.         return b;  
  272.     }  
  273.       
  274.     public static short bytesToShort(byte[] b){  
  275.         return (short)( b[1] & 0xff  
  276.                       |(b[0] & 0xff) << 8 );   
  277.     }  
  278.       
  279.     static void testShortConvert(){  
  280.         System.out.println("=================== short convert =============");  
  281.         System.out.println("byte2Hex(shortToBytes((short)0x11f2))"+byte2Hex(shortToBytes((short)0x11f2)));          
  282.         System.out.print("println 0x11f2:");  
  283.         System.out.println((short)0x11f2);          
  284.         System.out.println("byte2Hex(shortToBytes((short)0xf1f2))"+byte2Hex(shortToBytes((short)0xf1f2)));          
  285.         System.out.print("println 0xf1f2:");  
  286.         System.out.println((short)0xf1f2);              
  287.         System.out.print("println bytesToShort(shortToBytes((short)0x11f2)):");  
  288.         System.out.println((short)bytesToShort(shortToBytes((short)0x11f2)));              
  289.         System.out.print("println bytesToShort(shortToBytes((short)0xf1f2)):");  
  290.         System.out.println((short)bytesToShort(shortToBytes((short)0xf1f2)));          
  291.     }  
  292.       
  293.   
  294.     public static byte[] ushortToBytes(int n) {  
  295.         byte[] b = new byte[2];  
  296.         b[1] = (byte) (n & 0xff);  
  297.         b[0] = (byte) (n >> 8 & 0xff);  
  298.         return b;  
  299.     }  
  300.       
  301.   
  302.     public static int bytesToUshort(byte b[]) {  
  303.         return    b[1] & 0xff   
  304.                | (b[0] & 0xff) << 8;  
  305.     }  
  306.   
  307.     static void testUshortConvert(){  
  308.         System.out.println("=================== Ushort convert =============");  
  309.         System.out.println("byte2Hex(ushortToBytes(0x11f2))"+byte2Hex(ushortToBytes(0x11f2)));          
  310.         System.out.print("println 0x11f2:");  
  311.         System.out.println(0x11f2);          
  312.         System.out.println("byte2Hex(ushortToBytes(0xf1f2))"+byte2Hex(ushortToBytes(0xf1f2)));          
  313.         System.out.print("println 0xf1f2:");  
  314.         System.out.println(0xf1f2);              
  315.         System.out.print("println bytesToUshort(ushortToBytes(0x11f2)):");  
  316.         System.out.println(bytesToUshort(ushortToBytes(0x11f2)));              
  317.         System.out.print("println bytesToUshort(ushortToBytes(0xf1f2)):");  
  318.         System.out.println(bytesToUshort(ushortToBytes(0xf1f2)));          
  319.     }  
  320.       
  321.     public static byte[] ubyteToBytes( int n ){  
  322.         byte[] b = new byte[1];  
  323.         b[0] = (byte) (n & 0xff);  
  324.         return b;  
  325.     }  
  326.   
  327.     public static int bytesToUbyte( byte[] array ){              
  328.         return array[0] & 0xff;  
  329.     }      
  330.   
  331.     static void testUbyteConvert(){  
  332.         System.out.println("=================== Ubyte convert =============");  
  333.         System.out.println("byte2Hex(ubyteToBytes(0x1112))"+byte2Hex(ubyteToBytes(0x1112)));          
  334.         System.out.print("println 0x1112:");  
  335.         System.out.println(0x1112);          
  336.         System.out.println("byte2Hex(ubyteToBytes(0xf2))"+byte2Hex(ubyteToBytes(0xf2)));          
  337.         System.out.print("println 0xf2:");  
  338.         System.out.println(0xf2);              
  339.         System.out.print("println bytesToUbyte(ubyteToBytes(0x1112)):");  
  340.         System.out.println(bytesToUbyte(ubyteToBytes(0x1112)));              
  341.         System.out.print("println bytesToUbyte(ubyteToBytes(0xf1f2)):");  
  342.         System.out.println(bytesToUbyte(ubyteToBytes(0xf1f2)));          
  343.     }  
  344.       
  345.       
  346.     /** 
  347.      * @param args 
  348.      */  
  349.     public static void main(String[] args) {  
  350.         // TODO Auto-generated method stub          
  351.         byte[] array = new byte[4];  
  352.         array[3] = (byte0xF4;  
  353.         array[2] = 0x13;  
  354.         array[1] = 0x12;  
  355.         array[0] = 0x11;  
  356.           
  357.         System.out.println("=================== Integer bytes =============");  
  358.           
  359.         System.out.println("the bytes is:"+byte2Hex(array) );  
  360.         System.out.print("println bytesToInt :");  
  361.         System.out.println( bytesToInt(array));  
  362.         System.out.printf("printf bytesToInt :%X\n", bytesToInt(array));  
  363.           
  364.         System.out.println("=================== long bytes =============");  
  365.         byte[] longBytes = new byte[8];  
  366.           
  367.         longBytes[7] = (byte0xf7;  
  368.         longBytes[6] = (byte0x16;  
  369.         longBytes[5] = (byte0xf5;  
  370.         longBytes[4] = (byte0x14;  
  371.         longBytes[3] = (byte0xf3;  
  372.         longBytes[2] = (byte0x12;  
  373.         longBytes[1] = (byte0xf1;  
  374.         longBytes[0] = (byte0x10;  
  375.           
  376.   
  377.         System.out.println( "the bytes is:"+byte2Hex(longBytes) );  
  378.         System.out.printf("printf bytesToLong:%X\n",bytesToLong(longBytes));  
  379.           
  380.         System.out.println("=================byte to long ================");  
  381.           
  382.         byte b = (byte)0xf1;  
  383.         System.out.print("Println the byte:");  
  384.         System.out.println(b);  
  385.         System.out.printf("Printf the byte:%X\n",b);  
  386.         long l = b;  
  387.         System.out.print("Println byte to long:");  
  388.         System.out.println(l);  
  389.         System.out.printf("printf byte to long:%X\n",l);  
  390.           
  391.         System.out.println("================= uint Bytes ================");  
  392.           
  393.         byte[] uint = new byte[4];  
  394.         uint[3] = (byte0xf3;  
  395.         uint[2] = (byte0x12;  
  396.         uint[1] = (byte0xf1;  
  397.         uint[0] = (byte0xFF;  
  398.           
  399.         System.out.println( "the bytes is:"+byte2Hex(uint) );  
  400.         System.out.printf("printf bytesToUint:%X\n",bytesToUint(uint));  
  401.         System.out.print("Println bytesToUint:");  
  402.         System.out.println(bytesToUint(uint));  
  403.         System.out.println("byte2Hex(uintToBytes(0x11f2f3f4f5f6f7f8l)):"+byte2Hex(uintToBytes(0x11f2f3f4f5f6f7f8l)));  
  404.           
  405.         System.out.println("===============Long Integer==============");          
  406.         System.out.print("println 0x11f2f3f4f5f6f7f8l:");  
  407.         System.out.println(0x11f2f3f4f5f6f7f8l);          
  408.         System.out.printf("Printf 0x11f2f3f4f5f6f7f8l:%X\n",0x11f2f3f4f5f6f7f8l);  
  409.         System.out.println("println byte2Hex(longToBytes(0x11f2f3f4f5f6f7f8l))"+byte2Hex(longToBytes(0x11f2f3f4f5f6f7f8l)));  
  410.         // 注意,下面的这行,并不能获得正确的uint。  
  411.         System.out.printf("printf bytesToUint(longToBytes(0x11f2f3f4f5f6f7f8l):%X\n",bytesToUint(longToBytes(0x11f2f3f4f5f6f7f8l)));  
  412.           
  413.         System.out.println("===============bytesToLong(longToBytes())==============");  
  414.         System.out.println(bytesToLong(longToBytes(0x11f2f3f4f5f6f7f8l)));  
  415.         System.out.printf("%X\n",bytesToLong(longToBytes(0x11f2f3f4f5f6f7f8l)));  
  416.           
  417.         testShortConvert();  
  418.         testUshortConvert();  
  419.         testUbyteConvert();  
  420.     }  
  421.   
  422. }  


java中int与byte〔4〕的相互转换

http://www.cnblogs.com/mayola/archive/2011/11/17/2253101.html

我们都知道,JAVA中的基本数据类型有int,byte,char,long,float,double...,它们与引用数据类型很不一样,之所有在如此面向对象的JAVA语言中依然支持这些值类型,就是考虑到性能的原因。现在,同样是因为考虑到性能,我们需要一种高效的方法使int与byte[]能够自由的相互转换,理由就是,我们需要在网络上传送数据,而网络上的数据都是byte数据流,这就需要一个int-> byte[]与byte[] -> int的方法。
  简单的方法,我们可以用DataOutputStream与ByteArrayOutputStream来将int转换成byte[],方法就是:
        int i = 0;
        ByteArrayOutputStream boutput = newByteArrayOutputStream();
        DataOutputStream doutput = newDataOutputStream(boutput);
        doutput.writeInt(i);
         byte[] buf = boutput.toByteArray();
执行相反的过程我们就可以将byte[]->int,我们要用到DataInputStream与ByteArrayInputStream。
       byte[] buf = new byte[4];
        ByteArrayInputStream bintput = newByteArrayInputStream(buf);
        DataInputStream dintput = new DataInputStream();
         int i = dintput.readInt();
  上面的方法可以达到int<->byte[]的转化,下面还有更加高效的方法,虽然看起来会比较费劲一些,但是性能的提升是显而易见的。

[java] view plaincopy
  1. int -> byte[]  
  2.   
  3. privatebyte[] intToByteArray(final int integer) {  
  4. int byteNum = (40 -Integer.numberOfLeadingZeros (integer < 0 ? ~integer : integer))/ 8;  
  5. byte[] byteArray = new byte[4];  
  6.   
  7. for (int n = 0; n < byteNum; n++)  
  8. byteArray[3 - n] = (byte) (integer>>> (n * 8));  
  9.   
  10. return (byteArray);  
  11. }  
  12.   
  13.   byte[] -> int  
  14.   
  15. public static int byteArrayToInt(byte[] b, int offset) {  
  16.        int value= 0;  
  17.        for (int i = 0; i < 4; i++) {  
  18.            int shift= (4 - 1 - i) * 8;  
  19.            value +=(b[i + offset] & 0x000000FF) << shift;  
  20.        }  
  21.        return value;  
  22.  }  
  23. ========================================  
  24.   
  25. import java.io.*;  
  26.   
  27. public class IOTest {  
  28. public static void main(String[] args) throws Exception {  
  29.   int i = 65535;     
  30.   byte[] b = intToByteArray1(i);  
  31.   for(byte bb : b) {  
  32.    System.out.print(bb + " ");  
  33.   }  
  34. }  
  35.   
  36. public static byte[] intToByteArray1(int i) {     
  37.   byte[] result = new byte[4];     
  38.   result[0] = (byte)((i >> 24) & 0xFF);  
  39.   result[1] = (byte)((i >> 16) & 0xFF);  
  40.   result[2] = (byte)((i >> 8) & 0xFF);   
  41.   result[3] = (byte)(i & 0xFF);  
  42.   return result;  
  43. }  
  44.   
  45. public static byte[] intToByteArray2(int i) throws Exception {  
  46.   ByteArrayOutputStream buf = new ByteArrayOutputStream();     
  47.   DataOutputStream out = new DataOutputStream(buf);     
  48.   out.writeInt(i);     
  49.   byte[] b = buf.toByteArray();  
  50.   out.close();  
  51.   buf.close();  
  52.   return b;  
  53. }  

 

ByteArrayOutputStream用法

字节数组流:
ByteArrayOutputStream: 可以捕获内存缓冲区的数据,转换成字节数组。
ByteArrayoutputStream bout=new ByteArrayOutputStream();
bout.write(int a); bout.write(int b); bout.write(int c);
byte[] buf=bout.toByteArray();//获取内存缓冲中的数据
for(int i=0;i<=buf.length;i++)
{
System.out.println(buf);
}
bout.close();
注:通过调用reset()方法可以重新定位。
ByteArrayInputStream: 可以将字节数组转化为输入流
ByteArrayInputStream bin=new ByteArrayInputStream(byte[] buf);
int data=0;
while( (b=bin.read())!=-1)
{
System.out.println(b);
}
bin.close();

与DataOutputStream&DataInputStream联合使用:

ByteArrayOutputStream bout=new ByteArrayOutputStream();
DataOutputStream dos=new DataOutputStream(bout);
String name="suntao";
int age=19;
dos.writeUTF(name);
dos.writeInt(age);
byte[] buf=bout.toByteArray();//获取内存缓冲区中的数据
dos.close();
bout.close();

ByteArrayInputStream bin=new ByteArrayInputStream(byte[] buf);
DataInputStream dis=new DataInputStream(bin);
String name=dis.readUTF();//从字节数组中读取
int age=dis.readInt();
dis.close();
bin.close();

注: DataInputStream&DataOutputStream还可以与FileInputStream&FileOutputStream
联合使用。
其中:
DataInputStream&DataOutputStream关心如何将数据从高层次的形式转化成低层次的形式.
FileInputStream&FileOutputStream关心如何操作存储单元以接受和产生数据。

 

JAVA里面关于byte数组和String之间的转换问题

JAVA里面关于byte数组和String之间的转换问题 
  引自:http://soniccyj.bokee.com/6175850.html 
  JAVA里面关于byte数组和String之间的转换问题 
  把byte转化成string,必须经过编码。 
  例如下面一个例子: 
  import java.io.UnsupportedEncodingException; 
  public class test{ 
  public static void main(String g[]) { 
  String s = "12345abcd"; 
  byte b[] = s.getBytes(); 
  String t = b.toString(); 
  System.out.println(t); 
  } 
  } 
  输出字符串的结果和字符串s不一样了. 
  经过以下方式转码就可以正确转换了: 
  public class test{ 
  public static void main(String g[]) { 
  String s = "12345abcd"; 
  byte b[] = s.getBytes(); 
  try { 
  String t = new String(b); 
  System.out.print(t); 
  } catch (Exception e) { 
  e.printStackTrace(); 
  } 
  } 
  } 
  引自:http://topic.csdn.net/t/20050404/10/3906398.html 
  String str = "String"; 
  byte[] byte1 = str.getBytes(); 
  String str1 = new String(byte1); 
  byte[] byte2 = str1.getBytes(); 
  String str2 = new String(byte2); 
  System.out.println("str<<<" + str); 
  System.out.println("byte1<<<" + byte1); 
  System.out.println("str1<<<" + str1); 
  System.out.println("byte2<<<" + byte2); 
  System.out.println("str2<<<" + str2); 
  ------------------------------------- 
  输出结果 
  str<<<String 
  byte1<<<[B@192d342 
  str1<<<String 
  byte2<<<[B@6b97fd 
  str2<<<String 
  想请教为什么两个byte输出的不一样呢? 
  String str = "String"; 
  byte[] byte1 = str.getBytes(); 
  String str1 = new String(byte1); 
  byte[] byte2 = str1.getBytes(); 
  ---------- 
  注意byte1是str得到的byte数组,而byte2是另一个字符串str1得到的数组 
  他们本身也是两个对象 
  直接打印实际上调用的是toString()方法,而toString()的默认实现是打印对象类型+hashCode() 
  [B表示byte数组 
  @表示之后的是地址 
  后面跟着的是hashCode,其实就是其虚拟机地址 
  所以这个结果也就是顺理成章了.

最近的项目中要使用到把byte[]类型转换成String字符串然后通过网络发送,但发现发现出去的字符串和获取的字符串虽然是一样的,但当用String的getBytes()的方法得到的byte[]跟原来的byte[]是不一样的。

看如下代码:

 

bytebytes[] = new byte[] { 50, 0, -1, 28, -24 };

String string = new String(bytes);

byte[] ret = string.getBytes();

查看ret的数据发现是50, 0, -17, -65, -67, 28, -17, -65, -67,发现数据并不是原来的数据。

而使用如下代码就可以得到原来的数据:

 

bytebytes[] = new byte[] { 50, 0, -1, 28, -24 };

 

 

StringisoString = new String(bytes, "ISO-8859-1");

byte[] isoret = isoString.getBytes("ISO-8859-1");

这是为什么呢?原因是第一种方法默认是用UTF-8编码来生成String的,用System.getProperty("sun.jnu.encoding")可以得到Android默认编码是UTF-8。UTF-8是可变长度的编码,原来的字节数组就被改变了。而ISO8859-1通常叫做Latin-1,Latin-1包括了书写所有西方欧洲语言不可缺少的附加字符,其中 0~127的字符与ASCII码相同,它是单字节的编码方式,这样第二种方式生成的String里的字节数组就跟原来的字节数组一样。在new String使用其他编码如GBK,GB2312的话一样也会导致字节数组发生变化,因此要想获取String里单字节数组,就应该使用iso8859-1编码。

分享到:
评论
1 楼 GGGGeek 2017-09-21  
这总结的是相当详细了,可惜博主再也没有更新过博客了。。。

相关推荐

    ByteArrayOutputStream简介和使用_动力节点Java学院整理

    ByteArrayOutputStream 是字节数组输出流。它继承于OutputStream。 ByteArrayOutputStream 中的数据被写入一个 byte 数组。缓冲区会随着数据的不断写入而自动增长。可使用 toByteArray() 和 toString() 获取数据。

    java从输入流中获取数据并返回字节数组示例

    //从输入流中获取数据并以字节数组返回public class StreamTool { /** * 从输入流获取数据 * @param inputStream * @return * @throws Exception */ public static byte[] readInputStream(InputStream ...

    Java文件处理工具类--FileUtil

    * 从输入流读取数据为二进制字节数组. * @param streamIn * @return * @throws IOException */ public static byte[] readFileBinary(InputStream streamIn) throws IOException { BufferedInputStream...

    JAVA IO流缓冲字节流缓冲字符流等流经典代码示例加注释总结.rar

    2、常用21个IO流:FileWriter、FileReader、CharArrayReader、CharArrayWriter、CharSequence、OutputStreamWriter、FileOutputStream、InputStreamReader...演示错误用法和经典用法。 4、代码的结构可查看README文件。

    Java之IO流学习总结

    Reader 中各个类的用途和使用方法基本和InputStream 中的类使用一致。后面会有Reader 与InputStream 的对应关系。 5.字符输出流Writer 在上面的关系图中可以看出: Writer 是所有的输出字符流的父类,它是一个...

    java72-java-advance.rar

    a) 字符b)字节c)字节数组D)对象 4. 下列流中哪一个使用了缓冲区技术A A.BuffereOutputStream B. FileInputStream C. DataOutputStream D.FileReader 5.下列字节输入流中,哪一个不能够被实例化B A....

    详解Java中ByteArray字节数组的输入输出流的用法

    ByteArrayInputStream和ByteArrayOutputStream分别集成自InputStream和OutputStream这两个输入和输出流,这里我们就来详解Java中ByteArray字节数组的输入输出流的用法,需要的朋友可以参考下

    网络文件下载程序-基于Java源代码.rar

    网络文件下载程序-基于Java的源代码,给定一个文件的网络URL地址,本程序将从该地址获取(下载)文件,java环境的手机,可直接运行本程序,具体代码:  in = (InputStream) Connector.openInputStream(url); //...

    JAVA基础课程讲义

    JAVA.IO包相关流对象用法总结(尚学堂1002班王鑫) 165 IO中其他常用类 165 File类 165 RandomAccessFile 166 思考作业 166 上机作业 166 提高课外作业 166 第九章 多线程技术 167 基本概念 167 程序 167 进程 167 ...

    【IT十八掌徐培成】Java基础第16天-04.ByteArrayInputStream-ByteArrayOutputStream.zip

    【IT十八掌徐培成】Java基础第16天-04.ByteArrayInputStream-ByteArrayOutputStream.zip

    Java生成密钥的实例.rar

    Java生成密钥的实例  //产生单钥加密的密钥(myKey)  KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede"); //采用DESede算法  keyGenerator.init(168); //选择DESede算法,密钥长度为112位或168位...

    JDK_API_1_6

    ByteArrayOutputStream 此类实现了一个输出流,其中的数据被写入一个 byte 数组。 CharArrayReader 此类实现一个可用作字符输入流的字符缓冲区。 CharArrayWriter 此类实现一个可用作 Writer 的字符缓冲区。 ...

    IO体系.java

    InputStream ... |--ByteArrayOutputStream/:实现了一个输出流,其中的数据写入到一个byte数组。 | 使用toByteArray()和toString()获取数据。关闭无效,依然可以调用。不会产生任何IOException异常。

    java ZIP 解压缩

    java语言操作解压缩文件。 /** * 数据压缩 * * @param data * @return * @throws Exception */ public static byte[] compress(byte[] data) throws Exception { ByteArrayInputStream bais = new ...

    Java程序设计语言期末试题

    很好的Java复习资料,参考参考!对第28题的系统说明 如何应用DataInputStream进行文件操作 彻底明白Java的IO系统 一. Input和Output 1. stream代表的是任何有能力产出数据的数据源,或是任何有能力接收数据的接收...

    Java实现远程屏幕监视

    import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import ...

    TCP并发上传——java源码

    import java.io.*; import java.net.InetAddress; import java.net.UnknownHostException; public class ClientDemo { public static void main(String[] args) { try { InputStream in = new FileInputStream...

    Html2Image (JAVA)jar包

    Html2Image (JAVA)jar包public static byte[] generatePDF(StringReader strReader,String path) { try { FileOutputStream fos = new FileOutputStream(path); ByteArrayOutputStream os = new ...

    8583报文解析框架Simple8583.zip

    5)使用ByteArrayOutputStream将组装成的IsoPackage域值进行拼装成为一个大的byte数组,在byte前拼装两个字节的长度 6)通过Socket将数据发送并接受响应(读取前两个字节长度,根据长度获取其剩余报文),根据...

Global site tag (gtag.js) - Google Analytics