Java中的byte和二进制梳理

java byte 和Byte(来自https://www.cnblogs.com/SevenwindMa/p/3671057.html)

java的基本数据类型中有byte这种,byte存储整型数据,占据1个字节(8 bits),能够存储的数据范围是-128~+127。
Byte是java.lang中的一个类,目的是为基本数据类型byte进行封装。封装有几种好处,比如:1. Byte可以将对象的引用传递,使得多个function共同操作一个byte类型的数据,而byte基本数据类型是赋值之后要在stack(栈区域)进行存储的;2. 定义了和String之间互相转化的方法。Byte的大小是8个字节。因为Byte是需要通过关键字new来申请对象,而此部分申请出来的对象放在内存的heap(堆区域)。

public class ByteTest {
    public static void main(String args[])
    {
        Byte by1 = new Byte("123");
        Byte by2 = new Byte("123");
        int length = by1.SIZE;
         
        int max = by2.MAX_VALUE;
        int min = by2.MIN_VALUE;
         
        if(by1 == by2)
        {
            System.out.println("Operation '=' compares the reference of Byte objects and equal");
        }else System.out.println("Operation '=' compares the objects of Byte objects and not equal");
         
        if(by1.equals(by2))
        {
            System.out.println("Function 'equals()' compares the value of Byte objects and equal");
        }else System.out.println("Function 'equals()' compares the value of Byte objects and not equal");
         
        Byte by3 = by1;
        if(by3 == by1)
        {
            System.out.println("Operation '=' compares the reference of Byte objects and equal");
        }else System.out.println("Operation '=' compares the reference of Byte objects and not equal");
         
        System.out.println(by1);
        System.out.println(by2);
        System.out.println("The length is "+length);
        System.out.println("MAX:"+max+" MIN"+min);
        byte temp = (byte)241; // 241的二进制表示为11110001(补码),其中第一位为符号位,那么剩余的计算结果为15,最终结果为-15
        System.out.println(temp);
    }
 
}
运行结果:
Operation '=' compares the objects of Byte objects and not equal
Function 'equals()' compares the value of Byte objects and equal
Operation '=' compares the reference of Byte objects and equal
123
123
The length is 8
MAX:127 MIN-128
-15


Java byte[] 字节数组 转 二进制 八进制 十进制 十六进制字符串(来自http://blog.csdn.net/uikoo9/article/details/27980869)

【前言】
java中很多时候需要将byte[]转为各种进制的字符串显示,从2,8,10,16到比较高级的base64(编码),
至于什么时候需要这样,当你遇到这样的问题就知道了。

import java.math.BigInteger;  

public class QEncodeUtil {  
    public static void main(String[] args) {  
        String s = "woaini";  
        byte[] bytes = s.getBytes();  
          
        System.out.println("将woaini转为不同进制的字符串:");  
        System.out.println("可以转换的进制范围:" + Character.MIN_RADIX + "-" + Character.MAX_RADIX);  
        System.out.println("2进制:"   + binary(bytes, 2));  
        System.out.println("5进制:"   + binary(bytes, 5));  
        System.out.println("8进制:"   + binary(bytes, 8));  
        System.out.println("16进制:"  + binary(bytes, 16));  
        System.out.println("32进制:"  + binary(bytes, 32));  
        System.out.println("64进制:"  + binary(bytes, 64));// 这个已经超出范围,超出范围后变为10进制显示  
          
        System.exit(0);  
    }  
      
    /** 
     * 将byte[]转为各种进制的字符串 
     * @param bytes byte[] 
     * @param radix 基数可以转换进制的范围,从Character.MIN_RADIX到Character.MAX_RADIX,超出范围后变为10进制 
     * @return 转换后的字符串 
     */  
    public static String binary(byte[] bytes, int radix){  
        return new BigInteger(1, bytes).toString(radix);// 这里的1代表正数  
    }  
}
【输出】
将woaini转为不同进制的字符串:
可以转换的进制范围:2-36
2进制:11101110110111101100001011010010110111001101001
5进制:114203022342344442242
8进制:3566754132267151
16进制:776f61696e69
32进制:3ndtgmirj9
64进制:131320259374697

java怎么把一个byte变量按二进制输出(参考自https://zhidao.baidu.com/question/1115031702245345779.html和http://blog.csdn.net/qiantudou/article/details/49928423)

import java.util.Arrays;

public class hehe {
	/** 
     * 将byte转换为一个长度为8的byte数组,数组每个值代表bit 
     */  
    public static byte[] getBooleanArray(byte b) {  
        byte[] array = new byte[8];  
        for (int i = 7; i >= 0; i--) {  
            array[i] = (byte)(b & 1);  
            b = (byte) (b >> 1);  
        }  
        return array;  
    }  
    /** 
     * 把byte转为字符串的bit 
     */  
    public static String byteToBit(byte b) {  
        return ""  
                + (byte) ((b >> 7) & 0x1) + (byte) ((b >> 6) & 0x1)  
                + (byte) ((b >> 5) & 0x1) + (byte) ((b >> 4) & 0x1)  
                + (byte) ((b >> 3) & 0x1) + (byte) ((b >> 2) & 0x1)  
                + (byte) ((b >> 1) & 0x1) + (byte) ((b >> 0) & 0x1);  
    }
    
    public static void main(String args[]){
    	byte b = 0x35; // 0011 0101
    	// 输出 [0, 0, 1, 1, 0, 1, 0, 1]
    	System.out.println(Arrays.toString(getBooleanArray(b)));
    	// 输出 00110101
    	System.out.println(byteToBit(b));
    	// JDK自带的方法,会忽略前面的 0
    	System.out.println(Integer.toBinaryString(0x35));
    }
}
public class qie {
	public static void main(String args[]){
		byte tByte = -2;
		String tString = Integer.toBinaryString((tByte & 0xFF) + 0x100).substring(1);
		System.out.println("tString:" + tString);
		System.out.println(Integer.toBinaryString(tByte & 0xFF));
		System.out.println("---------------------");
		byte tByte2 = 2;
		System.out.println(Integer.toBinaryString((tByte2 & 0xFF) + 0x100).substring(1));
		System.out.println(Integer.toBinaryString(tByte2 & 0xFF));
	}
}
代码说明:
1、主要用到了Integer.toBinaryString方法转化为二进制的。但这个方法的参数是int型,所以需要先转换为int型。
2、转换为int型的方式:tByte & 0xFF
tByte: -2  如果自动转换为int型依旧为-2,但是 -2的int型转化为二进制是11111111111111111111111111111110。
因为java中是以补码的方式显示内容的,-2的二进制原码是 10000000000000000000000000000010,转化为反码+1为补码,就是上述数据了。
但是我们想要的是10000010的原码,补码为111111110。所以对上述数据进行 & 0xFF的操作。
这一步看不懂的请看https://wenku.baidu.com/view/e454c202ed630b1c59eeb5ea.html
还可以参考:
http://blog.csdn.net/xiekuntarena/article/details/53521656
http://blog.csdn.net/lvgaoyanh/article/details/53486933
https://www.cnblogs.com/think-in-java/p/5527389.html

Java中二进制和字符串之间的相互转换

案例一(参考自http://blog.csdn.net/lhjlhj123123/article/details/6384300)

public class hui {
    public static String byte2hex(byte[] b) { // 二进制转字符串  
        String hs = "";  
        String stmp = "";  
        for (int n = 0; n < b.length; n++) {  
         stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));  
         if (stmp.length() == 1)  
          hs = hs + "0" + stmp;  
         else  
          hs = hs + stmp;  
        }  
        return hs;  
     }  
   
     public static byte[] hex2byte(String str) { // 字符串转二进制  
        if (str == null)  
         return null;  
        str = str.trim();  
        int len = str.length();  
        if (len == 0 || len % 2 == 1)  
         return null;  
       
        byte[] b = new byte[len / 2];  
        try {  
         for (int i = 0; i < str.length(); i += 2) {  
          b[i / 2] = (byte) Integer  
            .decode("0x" + str.substring(i, i + 2)).intValue();  
         }  
         return b;  
        } catch (Exception e) {  
         return null;  
        }  
     }  
   
     public static void main(String[] args) {  
        String str = "abc";  
        String result = "";
        result = byte2hex(str.getBytes());  
        System.out.println(str.getBytes());  
        System.out.println(result);  
        System.out.println(new String(hex2byte(result)));  
        System.out.println(hex2byte(result).toString());  
     }  
}
运行结果:
[B@28154ec5
616263
abc
[B@1818a0a8

案例二(参考自http://blog.csdn.net/tangxufeng/article/details/4288106)

public class StrBinaryTurn {
    public static void main(String args[]){
    	BoolToStr(StrToBool("love"));
    }
	
    //将Unicode字符串转换成bool型数组
    public static boolean[] StrToBool(String input){
        boolean[] output=Binstr16ToBool(BinstrToBinstr16(StrToBinstr(input)));
        System.out.println(output);
        return output;
    }
    //将bool型数组转换成Unicode字符串
    public static String BoolToStr(boolean[] input){
        String output=BinstrToStr(Binstr16ToBinstr(BoolToBinstr16(input)));
        System.out.println(output);
        return output;
    }
    //将字符串转换成二进制字符串,以空格相隔
    private static String StrToBinstr(String str) {
        char[] strChar=str.toCharArray();
        String result="";
        for(int i=0;i<strChar.length;i++){
            result +=Integer.toBinaryString(strChar[i])+ " ";
        }
        return result;
    }
    //将二进制字符串转换成Unicode字符串
    private static String BinstrToStr(String binStr) {
        String[] tempStr=StrToStrArray(binStr);
        char[] tempChar=new char[tempStr.length];
        for(int i=0;i<tempStr.length;i++) {
            tempChar[i]=BinstrToChar(tempStr[i]);
        }
        return String.valueOf(tempChar);
    }
    //将二进制字符串格式化成全16位带空格的Binstr
    private static String BinstrToBinstr16(String input){
        StringBuffer output=new StringBuffer();
        String[] tempStr=StrToStrArray(input);
        for(int i=0;i<tempStr.length;i++){
            for(int j=16-tempStr[i].length();j>0;j--)
                output.append('0');
            output.append(tempStr[i]+" ");
        }
        return output.toString();
    }
    //将全16位带空格的Binstr转化成去0前缀的带空格Binstr
    private static String Binstr16ToBinstr(String input){
        StringBuffer output=new StringBuffer();
        String[] tempStr=StrToStrArray(input);
        for(int i=0;i<tempStr.length;i++){
            for(int j=0;j<16;j++){
                if(tempStr[i].charAt(j)=='1'){
                    output.append(tempStr[i].substring(j)+" ");
                    break;
                }
                if(j==15&&tempStr[i].charAt(j)=='0')
                    output.append("0"+" ");
            }
        }
        return output.toString();
    }   
    //二进制字串转化为boolean型数组  输入16位有空格的Binstr
    private static boolean[] Binstr16ToBool(String input){
        String[] tempStr=StrToStrArray(input);
        boolean[] output=new boolean[tempStr.length*16];
        for(int i=0,j=0;i<input.length();i++,j++)
            if(input.charAt(i)=='1')
                output[j]=true;
            else if(input.charAt(i)=='0')
                output[j]=false;
            else
                j--;
        return output;
    }
    //boolean型数组转化为二进制字串  返回带0前缀16位有空格的Binstr
    private static String BoolToBinstr16(boolean[] input){ 
        StringBuffer output=new StringBuffer();
        for(int i=0;i<input.length;i++){
            if(input[i])
                output.append('1');
            else
                output.append('0');
            if((i+1)%16==0)
                output.append(' ');           
        }
        output.append(' ');
        return output.toString();
    }
    //将二进制字符串转换为char
    private static char BinstrToChar(String binStr){
        int[] temp=BinstrToIntArray(binStr);
        int sum=0;   
        for(int i=0; i<temp.length;i++){
            sum +=temp[temp.length-1-i]<<i;
        }   
        return (char)sum;
    }
    //将初始二进制字符串转换成字符串数组,以空格相隔
    private static String[] StrToStrArray(String str) {
        return str.split(" ");
    }
    //将二进制字符串转换成int数组
    private static int[] BinstrToIntArray(String binStr) {       
        char[] temp=binStr.toCharArray();
        int[] result=new int[temp.length];   
        for(int i=0;i<temp.length;i++) {
            result[i]=temp[i]-48;
        }
        return result;
    }
}
运行结果:
[Z@7377711
love

  • 4
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值