zoukankan      html  css  js  c++  java
  • java byte 梳理

    最近写编解码的代码比较多,抽一点时间梳理下java下byte的解析。在例子代码中主要涉及的知识点就两块:

      1、byte代表8个bit,其中最高位是符号位

      2、当我们用String类的getBytes时,其实是默认采用某种编解码格式的,因此在例子中数字1被解析成49;

    public class App {
    
        public static void main(String[] args) throws UnsupportedEncodingException {
            
            
            byte a = 11;//总共8位,第一位是符号位
            
            for(int i = 0; i < 8; i++){
                System.out.printf("%d ", a >> i & 0x01);
            }//1 1 0 1 0 0 0 0
            
            System.out.println(" ");
            
            byte c = 0x11;
            
            for(int i = 0; i < 8; i++){
                System.out.printf("%d ", c >> i & 0x01);
            }//1 0 0 0 1 0 0 0
            
            System.out.println(" ");
            
            byte b = 1;
            b |= 0x01 << 7;
            for(int i = 0; i < 8; i++){
                System.out.printf("%d ", b >> i & 0x01);
            }//1 0 0 0 0 0 0 1 
            System.out.println(" ");
            System.out.println(b);//-127
            System.out.println(" ");
            
            byte d = Byte.parseByte("A", 16);
            
            for(int i = 0; i < 8; i++){
                System.out.printf("%d ", d >> i & 0x01);
            }//0 1 0 1 0 0 0 0
            
            System.out.println(" ");
            
            String i = Integer.toString(3);//3
            String j = Integer.toHexString(21);//15,采用16进制表示21
            
            System.out.printf("%s %s ", i, j);//3 15
            
            System.out.println(" ");
            
            //getBytes一定采用某种编码格式,若不填写则采用操作系统默认的格式
            byte[] data = j.getBytes("UTF-8");
            
            int ii = 0;
            int jj = 0;
            
            //在UTF-8编码下1被编码成49,注意不是十进制四十九,而是十进制四和九,同理编码五为五三;
            
            for( ii = 0; ii < data.length; ii++){
                
                System.out.println(data[ii]);//49 53
                
                for( jj = 0; jj < 8; jj++){
                    System.out.printf("%d ", data[ii] >> jj & 0x01);
                    if(7 == jj){
                        System.out.println(" ");
                    }
                }
                
                //1 0 0 0 1 1 0 0  ---> 4 9 
                //1 0 1 0 1 1 0 0  ---> 5 3
                
            }//for( ii = 0; ii < data.length; ii++){
            
        }
    }
  • 相关阅读:
    Ubuntu 18.04.2 LTS美化方案
    Ubuntu 16.04升级18.04
    Spark性能优化指南——高级篇
    Spark性能优化指南——基础篇
    遗传算法(Genetic Algorithm)——基于Java实现
    Linux sar命令参数详解
    Gdb调试多进程程序
    P8.打印整数
    Algorithm Book Index
    Debugging with GDB (8) 4.10 Debugging Programs with Multiple Threads
  • 原文地址:https://www.cnblogs.com/Fredric-2013/p/6605253.html
Copyright © 2011-2022 走看看