萍聚社区-德国热线-德国实用信息网

 找回密码
 注册

微信登录

微信扫一扫,快速登录

萍聚头条

查看: 772|回复: 0

1-1-12-4 一个int与byte array之间的转换程序

[复制链接]
发表于 2003-2-7 01:48 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?注册 微信登录

x

  1. 发信人: qyjohn (Sweet Potato -- 成功戒BBS中...), 信区: Java      
  2. 标  题: 一个int与byte array之间的转换程序
  3. 发信站: BBS 水木清华站 (Tue Jun  5 01:05:43 2001)

  4. 在通讯中经常需要将数值转换成字节流,或者是将字节流转换成数值。下面
  5. 提供的程序可以进行int和byte array之间的转换。

  6. 在以后一段时间内还将编制浮点数和双精度浮点数与字节流之间的转换程序
  7. 并与大家分享。欢迎测试和提出意见。

  8. /**
  9. *
  10. * IntConverter
  11. *
  12. * This class provides methods to convert int into byte array and
  13. * byte array back into int.
  14. *
  15. */


  16. public class IntConverter
  17. {
  18.         /**
  19.          *
  20.          * Method converting int into byte array.
  21.          *
  22.          * @param number The int value to be converted.
  23.          *
  24.          */
  25.         
  26.         public static byte[] toByteArray(int number)
  27.         {
  28.             int temp = number;
  29.             byte[] b=new byte[4];
  30.             for (int i = b.length - 1; i > -1; i--)
  31.             {
  32.                 b[i] = new Integer(temp & 0xff).byteValue();
  33.                 temp = temp >> 8;
  34.             }
  35.             return b;
  36.         }

  37.         /**
  38.          *
  39.          * Method converting byte array into int.
  40.          *
  41.          * @param The byte array to be converted.
  42.          *
  43.          */

  44.         public static int toInteger(byte[] b)
  45.         {
  46.             int s = 0;
  47.                
  48.             for (int i = 0; i < 3; i++)
  49.             {
  50.                 if (b[i] > 0)
  51.                     s = s + b[i];
  52.                 else
  53.                     s = s + 256 + b[i];
  54.                 s = s * 256;
  55.             }
  56.         
  57.             if (b[3] > 0)
  58.                 s = s + b[3];
  59.             else
  60.                 s = s + 256 + b[3];
  61.                
  62.             return s;
  63.         }
  64.         
  65.     // Testing program.

  66.     public static void main(String[] args)
  67.     {
  68.         IntConverter abc = new IntConverter();
  69.         int s = -1121115678;
  70.         byte[] b = abc.toByteArray(s);
  71.         for (int i = 0; i <= 3; i++)
  72.                 System.out.println(b[i]);
  73.                
  74.         s = abc.toInteger(b);
  75.         System.out.println(s);                  
  76.     }
  77. }
复制代码
Die von den Nutzern eingestellten Information und Meinungen sind nicht eigene Informationen und Meinungen der DOLC GmbH.
您需要登录后才可以回帖 登录 | 注册 微信登录

本版积分规则

手机版|Archiver|AGB|Impressum|Datenschutzerklärung|萍聚社区-德国热线-德国实用信息网 |网站地图

GMT+2, 2024-5-21 16:57 , Processed in 0.067535 second(s), 19 queries , MemCached On.

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表