zoukankan      html  css  js  c++  java
  • 将一个十进制转换为二进制,八进制,十六进制

    package com.db2;
    
    /**
     * 将一个十进制转换为二进制,八进制,十六进制
     * 
     * @author denny
     *
     */
    public class Demo2 {
    
        public static void main(String[] args) {
            toBin(6);
            toBin(-6);
            toOct(60);
            toOct(-60);
            toHex(60);
            toHex(-60);
        }
    
        // 转换2进制
        public static void toBin(int num) {
    
            toTran(num, 1, 1);// 1是2进制最大值,二进制只有0,1,1位右移
        }
    
        // 八进制
        public static void toOct(int num) {
    
            toTran(num, 7, 3);// 7是2进制最大值,八进制只有0-7最大是7,3位2进制表示一个八进制右移3位
        }
    
        // 十六进制
        public static void toHex(int num) {
    
            toTran(num, 15, 4);// 15是十六进制最大值,十六进制只有0-15最大是15,4位2进制表示一个八进制右移4位
        }
    
        // 转换函数
        private static void toTran(int num, int base, int offset) {// num要转换的数,求与的数,右移的数
            char[] ch = { '0','1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; // 十六进制元素同时包含2,进制,八进制
            // 存储转换过的数 //最大只有32位
            char[] arr = new char[32];
            // 定义控制数组的下标
            int pos = arr.length;
            // 开始转换
            while (num != 0) {
                int temp = num & base;// 与位
                arr[--pos] = ch[temp]; // 找到并存储
                num = num >>> offset;
            }
            // 输出
            for (int i = pos; i < arr.length; i++) {
                System.out.print(arr[i]);
            }
            System.out.println();
        }
    
    }
  • 相关阅读:
    Python循环语句
    Python简单的语句组
    Jedis 之 初始<一>
    微信小程序登入流程
    微信小程序发起请求
    django数据库迁移时候异常
    Git常用命令总结
    微信小程序自定义组件
    POJ3345 Bribing FIPA
    POJ1947 Rebuilding Roads
  • 原文地址:https://www.cnblogs.com/liunanjava/p/4785951.html
Copyright © 2011-2022 走看看