Java 字符串格式化

整数转二进制

  Integer  t = (1 << 29) -1;
  System.out.println(String.format("%32s", Integer.toBinaryString(t)).replace(" ", "0"));

  输出: 00011111111111111111111111111111

Long(大于1) 转二进制

/**
 * @Author : LukeRen
 * @DateTime: 2021/9/2 10:59
 * @Description : Long 转 二进制 字符串工具类
 * @Version : 1.0
 */
public class DigitToBinStrRepresent {

    /**
     * 使用法则: 除二取余,然后倒序排列,高位补零
     * 如: 83除以2得到的余数分别为1100101,倒着排一下,83所对应二进制就是1010011, 位数不够高位补0, 如需要8位二进制 : 01010011
     *  未做负数的转换
     * @param val       long 型整数
     * @return
     */
    public static String  longToBinStr(Long val){
        if (val < 1){
            throw new RuntimeException("参数必须大于1");
        }
        Stack<Long> binDesc = new Stack<>();
        //被除数
        Long dividend = val;
        //商
        Long quotient = dividend;
        while (quotient >= 1) {
            //余数
            Long remainder = dividend % 2;
            quotient = dividend / 2;
            binDesc.push(remainder);
            dividend = quotient;
        }

        StringBuffer stringBuffer = new StringBuffer();
        while (!binDesc.empty()) {
            stringBuffer.append(binDesc.pop());
        }

        //转换成64为二进制位, 高位不够补0;
        String binStr = String.format("%64s", stringBuffer).replaceAll(" ", "0");
        //每4位加一个空格
        binStr = binStr.replaceAll("(.{4})", "$1 ");
        return binStr;
    }

    public static void main(String[] args) {
        System.out.println(longToBinStr(255L));
        //结果: 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 1111 1111
    }

}

posted @ 2021-03-31 14:00  那年长安  阅读(178)  评论(0编辑  收藏  举报