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++){
            
        }
    }
  • 相关阅读:
    Core Animation系列之CADisplayLink(转)
    由App的启动说起(转)
    Xcode断点的一些黑魔法
    好代码的标准
    Java JPS找不到正在执行的java进程 jps cannot see running java process
    JetBrain server certificate is not trusted 弹出框
    Window7 定制 Explore中的右键菜单
    Go语言入门: Chapter1
    针对缓存在Redis中的聊天消息的持久化方案分析
    轻型Database- sqlite入门
  • 原文地址:https://www.cnblogs.com/Fredric-2013/p/6605253.html
Copyright © 2011-2022 走看看