java基本数据转换

来源:互联网 发布:数控车床内螺纹编程 编辑:程序博客网 时间:2024/04/28 16:40

1,字符串->整数

需求 代码 备注 string->int Integer.parse(“123”) hexstring->int Integer.parse(“FF00”,16) 可以指定解码哪种进制,但前面不带0x之类 通用带格式string->int Integer.decode(“0xAABB”) 支持前面带格式自动判断几进制

2,整数->字符串

需求 代码 备注 int->string Integer.toString(123) int->hexstring Integer.toHexString(123) uint->string Integer.toUnsignedString(-1,radix) 显示无符号整数结果 uint->二进制串 Integer.toBinaryString(123) uint->通用格式串 String.format(“%d%x…”,…)

2,字节数组读写short/int/long

类似c++中的字节指针读写short/int,(short)p,(int)p
又分为小端和大端模式,htonl,htons
代码存在于java.io.Bits和java.nio.Bits及java.nio.ByteBuffer,但前两者为私有类无法使用,ByteBuffer则要先wrap(byte[])创建对象不妥。

public class BytePtr {    public static short swap(short x)  { return Short.reverseBytes(x);   }    public static int   swap(int x)    { return Integer.reverseBytes(x);    }        public static short htons(short x) { return Short.reverseBytes(x);   }    public static int   htonl(int x)   { return Integer.reverseBytes(x);    }       public static short makeShort(byte b1, byte b0) { return (short)((b1 << 8) | (b0 & 0xff));    }    public static int   makeInt(byte b3,byte b2,byte b1,byte b0) {return (((b3 ) << 24) | ((b2 & 0xff) << 16) | ((b1 & 0xff) <<  8) | ((b0 & 0xff)  )); }    public static byte short1(short x) { return (byte)(x >> 8); }    public static byte short0(short x) { return (byte)(x     ); }    public static byte int3(int x) { return (byte)(x >> 24); }    public static byte int2(int x) { return (byte)(x >> 16); }    public static byte int1(int x) { return (byte)(x >>  8); }    public static byte int0(int x) { return (byte)(x      ); }    public static short getShortL(byte[] buf, int offset) {  return makeShort(buf[offset+1] , buf[offset  ]);   }    public static short getShortB(byte[] buf, int offset) {  return makeShort(buf[offset  ] , buf[offset+1]);   }    public static void putShortL(byte[] buf, int offset, short x) { buf[offset] = short0(x);    buf[offset+1] = short1(x); }    public static void putShortB(byte[] buf, int offset, short x) { buf[offset] = short1(x);    buf[offset+1] = short0(x); }    public static int getIntL(byte[] buf, int offset) { return makeInt(buf[offset+3],buf[offset+2],buf[offset+1],buf[offset  ]); }    public static int getIntB(byte[] buf, int offset) { return makeInt(buf[offset  ],buf[offset+1],buf[offset+2],buf[offset+3]); }      public static void putIntL(byte[] buf,int offset,int x) {buf[offset]=int0(x);buf[offset+1]=int1(x);buf[offset+2]=int2(x);buf[offset+3]=int3(x);}    public static void putIntB(byte[] buf,int offset,int x) {buf[offset]=int3(x);buf[offset+1]=int2(x);buf[offset+2]=int1(x);buf[offset+3]=int0(x);}}

3,字节数组->字符串

Arrays.toString()
Array.asStream().map(String::toHexString).reduce(“”,String::concat))

0 0
原创粉丝点击