java基本数据转换

1,字符串->整数

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

2,整数->字符串

需求代码备注
int->stringInteger.toString(123)
int->hexstringInteger.toHexString(123)
uint->stringInteger.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
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值