test2.java 2.56 KB
package com.huaheng.test;

public class test2 {

    //int转byte[]  高字节在前(高字节序)
    public static byte[] toByteArray(int n) {
        byte[] b = new byte[4];
        b[3] = (byte) (n & 0xff);
        b[2] = (byte) (n >> 8 & 0xff);
        b[1] = (byte) (n >> 16 & 0xff);
        b[0] = (byte) (n >> 24 & 0xff);
        return b;
    }

    //int的二进制表示  高字节在前(高字节序)
    public static StringBuilder intToBinary(int num){
        StringBuilder str = new StringBuilder();
//        for(int i=31;i>=0;i--){
//           str.append((num & (1 <<i))==0?"0":"1");
//        }
        for(int i=15;i>=0;i--){
            str.append((num & (1 <<i))==0?"0":"1");
        }
//        System.out.println();
        return str;
    }

    //byte数组的二进制表示
    public static String byteArrayToBinary(byte[] bytes){
        StringBuilder str = new StringBuilder();
        for (byte b : bytes) {
            String tString = Integer.toBinaryString((b & 0xFF) + 0x100).substring(1);
            str.append(tString);
        }
        System.out.println(str.toString());
        return str.toString();
    }

    public static void main(String[] args) {
        int a=512;
        int bit=9;
//        intToBinary(a);
//        intToBinary(a>>1);
//        byte[] bytes = toByteArray(256);
//        byteArrayToBinary(bytes);
        //System.out.println(intBitArithmetic(a,bit));

    }
    //用于写 num读到的值,bit往哪个位写值,flag写几0/1
    public static int xie(int num,int bit,String flag){
        StringBuilder stringBuilder = intToBinary(256);
        stringBuilder.replace(15-bit,16-bit,flag);
        return Integer.parseInt(stringBuilder.toString(), 2);
    }

    //int类型时 进行位运算,位移多少位   用于读
    public static boolean intBitArithmetic(int num,int bit){
        if(num==(num & (1 << bit))){
            return true;
        }else {
            return false;
        }
    }

    //字符串转二进制
    public static String toBinary(String str)
    {

        char[] strChar = str.toCharArray();

        int [] a=new int[str.length()];
        for(int i=0;i<str.length();i++)
        {
            a[i]=strChar[i];
        }

        String result = "";
        for(int i = 0; i < strChar.length; i++)
        {
            if(Integer.toBinaryString(a[i]).length()<7)
            {
                result+="0"+Integer.toBinaryString(a[i])+" ";
            }
            else
            {
                result += Integer.toBinaryString(a[i]) + " ";
            }
        }
        return result;
    }


}