天天看點

密碼學之Byte和bit

前言

Byte : 位元組. 資料存儲的基本機關,比如移動硬碟1T , 機關是byte

bit : 比特, 又叫位. 一個位要麼是0要麼是1. 資料傳輸的機關 , 比如家裡的寬帶100MB,下載下傳速度并沒有達到100MB,一般都是12-13MB,那麼是因為需要使用 100 / 8

關系: 1Byte = 8bit

一、擷取字元串byte

package com.atguigu.bytebit;
/**
 * @author JsonHao😋
 * @date 2020年9月10日 下午10:58:59
 */
public class ByteBit {
    public static void main(String[] args) {
        String a = "a";
        byte[] bytes = a.getBytes();
        for (byte b : bytes) {
            int c=b;
            // 列印發現byte實際上就是ascii碼
            System.out.println(c);
        }
    }
}      

二、 byte對應bit

package com.atguigu.bytebit;

/**
 * @author JsonHao😋
 * @date 2020年9月10日 下午10:58:59
 */
public class ByteBit {
    public static void main(String[] args) {
        String a = "a";
        byte[] bytes = a.getBytes();
        for (byte b : bytes) {
            int c=b;
            // 列印發現byte實際上就是ascii碼
            System.out.println(c);
            // 我們在來看看每個byte對應的bit,byte擷取對應的bit
            String s = Integer.toBinaryString(c);
            System.out.println(s);
        }
    }
}

      

三、 中文對應的位元組

// 中文在GBK編碼下, 占據2個位元組
// 中文在UTF-8編碼下, 占據3個位元組
package com.atguigu;

/**
 * @author JsonHao😋
 * @date 2020年9月10日 下午11:09:16
 */
public class ByteBitDemo {
    public static void main(String[] args) throws Exception{

        String a = "尚";
        byte[] bytes = a.getBytes();
        for (byte b : bytes) {
            System.out.print(b + "   ");
            String s = Integer.toBinaryString(b);
            System.out.println(s);
        }
    }    
}



      

運作程式:我們發現一個中文是有 3 個位元組組成

我們修改 編碼格式 , 編碼格式改成 GBK ,我們在運作發現變成了 2 個位元組

public static void main(String[] args) throws Exception {
  String a = "尚";
  // 在中文情況下,不同的編碼格式,對應不同的位元組
  // GBK :編碼格式占2個位元組
  // UTF-8:編碼格式占3個位元組
  byte[] bytes = a.getBytes("GBK");
  // byte[] bytes = a.getBytes("UTF-8");
  for (byte b : bytes) {
    System.out.print(b + "   ");
    String s = Integer.toBinaryString(b);
    System.out.println(s);
  }
    }      

四、 英文對應的位元組

我們在看看英文,在不同的編碼格式占用多少位元組

package com.atguigu.bytebit;

/**
 * @author JsonHao😋
 * @date 2020年9月10日 下午10:58:59
 */
public class ByteBit {
    public static void main(String[] args) throws Exception {
        String a = "A";
        byte[] bytes = a.getBytes();
        //在中文情況下,不同的編碼格式,對應不同的位元組
        //byte[] bytes = a.getBytes("GBK");
        for (byte b : bytes) {
            System.out.print(b + "   ");
            String s = Integer.toBinaryString(b);
            System.out.println(s);
        }
    }
}

      

運作程式

密碼學之Byte和bit