Byte和bit
1.概述
2.获取字符串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);
}
}
}
运行程序
3.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);
}
}
}
4.中文对应的字节
// 中文在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);
}
}
}
我们修改编码格式 , 编码格式改成 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);
}
}
5.英文对应的字节
我们在看看英文,在不同的编码格式占用多少字节
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);
}
}
}
package com.atguigu.bytebit;
/**
* ByteBit
*
* @Author: 马伟奇
* @CreateTime: 2020-05-05
* @Description:
*/
public class ByteBit {
public static void main(String[] args) {
String a = "a";
byte[] bytes = a.getBytes();
for (byte aByte : bytes) {
int c = aByte;
System.out.println(c);
// byte 字节,对应的bit是多少
String s = Integer.toBinaryString(c);
System.out.println(s);
}
}
}
package com.atguigu.bytebit;
/**
* ByteBitDemo
*
* @Author: 马伟奇
* @CreateTime: 2020-05-05
* @Description:
*/
public class ByteBitDemo {
/**
* 根据编码的格式不一样,对应的字节也不一样
* 如果是UTF-8:一个中文对应的是三个字节
* 如果是GBK : 一个中文对应的是二个字节
*
* 如果是英文,就无所谓编码格式
*/
public static void main(String[] args) throws Exception{
String a = "A";
byte[] bytes = a.getBytes();
for (byte aByte : bytes) {
System.out.println(aByte);
String s = Integer.toBinaryString(aByte);
System.out.println(s);
}
}
}