Byte和bit
Byte : 字節. 數據存儲的基本單位,比如移動硬盤1T , 單位是byte
bit : 比特, 又叫位. 一個位要麼是0要麼是1. 數據傳輸的單位 , 比如家裏的寬帶100MB,下載速度並沒有達到100MB,一般都是12-13MB,那麼是因爲需要使用 100 / 8
關係: 1Byte = 8bit
獲取字符串byte
package com.atguigu.bytebit;
/**
* ByteBit
*
* @Author: 尚硅谷
* @CreateTime: 2020-03-17
* @Description:
*/
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;
/**
* ByteBit
*
* @Author: 尚硅谷
* @CreateTime: 2020-03-17
* @Description:
*/
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);
}
}
}
運行程序
打印出來應該是8個bit,但前面是0,沒有打印 ,從打印結果可以看出來,一個英文字符 ,佔一個字節
中文對應的字節
// 中文在GBK編碼下, 佔據2個字節
// 中文在UTF-8編碼下, 佔據3個字節
package com.atguigu;
/**
* ByteBitDemo
*
* @Author: 尚硅谷
* @CreateTime: 2020-03-16
* @Description:
*/
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;
/**
* ByteBit
*
* @Author: 尚硅谷
* @CreateTime: 2020-04-12
* @Description:
*/
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);
}
}
}