ITeye博客

关于Soeckt 流操作的数据转换工具方法

damies · 2007-11-02 10:50 · JAVA技术 · Markdown

java 代码

  1. package com.sunhill.k1c.sms.util;
  2. import java.nio.*;
  3. //数据转换
  4. /**
  5. *create by Shane about dataconvert
  6. *PCCW BJ DEV
  7. */
  8. public class DataConvertUtil {
  9. public static int byte2int(byte[] b){
  10. return b[3] & 0xff | (b[2] & 0xff) << 8 | (b[1] & 0xff) << 16 | (b[0] & 0xff) << 24;
  11. }
  12. public static byte[] int2Byte(int value){
  13. byte[] b=new byte[4];
  14. ByteBuffer buffer = ByteBuffer.allocate(4);
  15. buffer.asIntBuffer().put(value);
  16. for(int i=0;i<4;i++){
  17. b[i]= buffer.get();
  18. }
  19. return b;
  20. }
  21. public static long byte2uint(byte b[]) {
  22. return (long)b[3] & (long)255 | ((long)b[2] & (long)255) << 8 | ((long)b[1] & (long)255) << 16 | ((long)b[0] & (long)255) << 24;
  23. }
  24. public static byte[] uint2byte(long value) {
  25. byte b[] = new byte[4];
  26. b[0] = (byte)(int)(value >> 24);
  27. b[1] = (byte)(int)(value >> 16);
  28. b[2] = (byte)(int)(value >> 8);
  29. b[3] = (byte)(int)value;
  30. return b;
  31. }
  32. public static String byte2String(byte[] b){
  33. return new String(b);
  34. }
  35. public static byte[] getSubByte(byte[] buffer,int from,int len){
  36. if(from+len>buffer.length){
  37. len=buffer.length-from;
  38. }
  39. byte[] b = new byte[len];
  40. for(int i=0;i<len;i++){
  41. b[i]= buffer[i+from];
  42. }
  43. return b;
  44. }
  45. public static void setSubByte(byte[] dest, byte[] src,int from,int len){
  46. if(dest==null){
  47. return;
  48. }
  49. if(from+len>dest.length){
  50. return;
  51. }
  52. if(src!=null){
  53. for(int i=0;i<len;i++){
  54. if(i>=src.length){
  55. dest[i+from]=0;
  56. }else{
  57. dest[i+from]=src[i];
  58. }
  59. }
  60. }else{
  61. for(int i=0;i<len;i++){
  62. dest[i+from]=0;
  63. }
  64. }
  65. }
  66. }

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。