开发者

How to convert numbers to binary and hex (without built-in functions)?

开发者 https://www.devze.com 2023-03-14 05:02 出处:网络
Since this is homework, I can\'t use built-in functions. I have to use algorithms in Java. This is what I have so far but it is wrong.

Since this is homework, I can't use built-in functions. I have to use algorithms in Java.

This is what I have so far but it is wrong.

import java.util.Scanner;

public class ChangingFigures {
    public static void main (String开发者_高级运维[] args){
        Scanner scanner = new Scanner (System.in);
        System.out.print("Enter an integer between 0 and 127:");

        int num = scanner.nextInt ();

        String hex = Integer.toHexString(num);
        String bin = Integer.toBinaryString(num); 
        // ...
    }
}


The algorithm is trivial:

make an empty string
do:
    prepend "n" modulo "base" to that string
    divide "n" by "base"
until (n == 0)

if "base" is greater than 10 you'll need to do a little work to convert the "digits" into the letters that represent 10+


To HEX:

String HEXES = "0123456789ABCDEF";
System.out.println(HEXES.charAt((num & 0xF0) >> 4) + "" + HEXES.charAt((num & 0x0F)));

To binary

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号