short,int,long与byte数组之间的转换

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

1.

2.package com.test;

3.

4.import java.nio.ByteBuffer;

5.

6.public class ByteUtil {

7.

8./**

9. * @param args

10. */

11. public static void main(String[] args) {

12. test2();

13. }

14. public static void test2()

15. {

16. short s = -20;

17. byte[] b = new byte[2];

18. putReverseBytesShort(b, s, 0);

19. ByteBuffer buf = ByteBuffer.allocate(2);

20. buf.put(b);

21. buf.flip();

22. System.out.println(getReverseBytesShort(b, 0));

23. System.out.println(Short.reverseBytes(buf.getShort()));

24. System.out.println("***************************");

25. int i = -40;

26. b = new byte[4];

27. putReverseBytesInt(b, i, 0);

28. buf = ByteBuffer.allocate(4);

29. buf.put(b);

30. buf.flip();

31. System.out.println(getReverseBytesInt(b, 0));

32. System.out.println(Integer.reverseBytes(buf.getInt()));

33. System.out.println("***************************");

34. long l = -50;

35. b = new byte[8];

36. putReverseBytesLong(b, l, 0);

37. buf = ByteBuffer.allocate(8);

38. buf.put(b);

39. buf.flip();

40. System.out.println(getReverseBytesLong(b, 0));

41. System.out.println(Long.reverseBytes(buf.getLong()));

42. System.out.println("***************************");

43. }

44. public static void test1()

45. {

46. short s = -20;

47. byte[] b = new byte[2];

48. putShort(b, s, 0);

49. ByteBuffer buf = ByteBuffer.allocate(2);

50. buf.put(b);

51. buf.flip();

52. System.out.println(getShort(b, 0));

53. System.out.println(buf.getShort());

54. System.out.println("***************************");

55. int i = -40;

56. b = new byte[4];

57. putInt(b, i, 0);

58. buf = ByteBuffer.allocate(4);

59. buf.put(b);

60. buf.flip();

61. System.out.println(getInt(b, 0));

62. System.out.println(buf.getInt());

63. System.out.println("***************************");

64. long l = -50;

65. b = new byte[8];

66. putLong(b, l, 0);

67. buf = ByteBuffer.allocate(8);

68. buf.put(b);

69. buf.flip();

70. System.out.println(getLong(b, 0));

71. System.out.println(buf.getLong());

72. System.out.println("***************************");

73. }

74. public static void putShort(byte b[], short s, int index)

{

75. b[index] = (byte) (s >> 8);

76. b[index + 1] = (byte) (s >> 0);

77. }

78. public static void putReverseBytesShort(byte b[], short s,

int index) {

79. b[index] = (byte) (s >> 0);

80. b[index + 1] = (byte) (s >> 8);

81. }

82. public static short getShort(byte[] b, int index) {

83. return (short) (((b[index] << 8) | b[index + 1] & 0xff)

);

84. }

相关文档
最新文档