|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?注册
x
- 发信人: qyjohn (Sweet Potato -- 成功戒BBS中...), 信区: Java
- 标 题: 一个int与byte array之间的转换程序
- 发信站: BBS 水木清华站 (Tue Jun 5 01:05:43 2001)
- 在通讯中经常需要将数值转换成字节流,或者是将字节流转换成数值。下面
- 提供的程序可以进行int和byte array之间的转换。
- 在以后一段时间内还将编制浮点数和双精度浮点数与字节流之间的转换程序
- 并与大家分享。欢迎测试和提出意见。
- /**
- *
- * IntConverter
- *
- * This class provides methods to convert int into byte array and
- * byte array back into int.
- *
- */
- public class IntConverter
- {
- /**
- *
- * Method converting int into byte array.
- *
- * @param number The int value to be converted.
- *
- */
-
- public static byte[] toByteArray(int number)
- {
- int temp = number;
- byte[] b=new byte[4];
- for (int i = b.length - 1; i > -1; i--)
- {
- b[i] = new Integer(temp & 0xff).byteValue();
- temp = temp >> 8;
- }
- return b;
- }
- /**
- *
- * Method converting byte array into int.
- *
- * @param The byte array to be converted.
- *
- */
- public static int toInteger(byte[] b)
- {
- int s = 0;
-
- for (int i = 0; i < 3; i++)
- {
- if (b[i] > 0)
- s = s + b[i];
- else
- s = s + 256 + b[i];
- s = s * 256;
- }
-
- if (b[3] > 0)
- s = s + b[3];
- else
- s = s + 256 + b[3];
-
- return s;
- }
-
- // Testing program.
- public static void main(String[] args)
- {
- IntConverter abc = new IntConverter();
- int s = -1121115678;
- byte[] b = abc.toByteArray(s);
- for (int i = 0; i <= 3; i++)
- System.out.println(b[i]);
-
- s = abc.toInteger(b);
- System.out.println(s);
- }
- }
复制代码 |
|