使用重载方法将数字转换为二进制形式

时间:2015-01-18 04:43:27

标签: java

我正在使用下一个代码,它基本上将十六进制数转换为二进制形式。首先,我必须声明一个变量类型int,byte或short,然后使用十六进制数来使用它,然后它必须打印二进制数,如下所示:

int h = 0x1 - > 00000000 | 00000000 | 00000000 | 00000001(32因为int有32位)

字节h = 0x1 - > 00000001(字节有8位)

短h = 0x1 - > 00000000 | 00000001(短有16位)

我已经有了转换它的函数,并且工作正常,问题是我必须创建三个重载方法(一个用于int,另一个用于简短,另一个用于byte),参数将是十六进制数字和类型,但如何在不使用Java API的情况下获取变量的类型(我不允许使用它)。

public class Bits {

    public static void main(String[] args){
        int value = 0xFFFFFFFF;
        memoryRAM(value);
    }

    public static void memoryRAM(int value)
    {
        int i,bits;
        bits = 32;
        char binary[] = new char[bits];
        for(i = bits-1;i >= 0;i--)
        {
            if((value&1) == 1)
               binary[i] = '1';
            else if((value&1) == 0)
               binary[i] = '0';
            value >>= 1;
        }
        printArray(binary);
    }

    public static void printArray(char binary[]){
        for(int i = 0;i < binary.length;i++)
            System.out.print(""+binary[i]);
    }
}

到目前为止,我已经使用value参数创建了该方法,但是我需要另一个带有变量类型的参数(int,short,byte)。

1 个答案:

答案 0 :(得分:1)

有三个方法,每个类型一个,将自动将变量排序为正确的方法,并从那里,你可以硬编码方法来进行特定类型的计算

例如,如果你有:

public static void main(String[] args){
    byte b = 4;
    int i = 1000;
    short s = 123;
    someMethod(b); //this will automatically choose the "byte" method
    someMethod(i); //this will automatically choose the "int" method
    someMethod(s); //this will automatically choose the "short" method
}

public static void someMethod(byte b){
    //do byte specific stuff
}

public static void someMethod(int i){
    //do int specific stuff
}

public static void someMethod(short s){
    //do short specific stuff
}

或获取原始变量的类型:

byte b = 4;
String type = "";

if(byte.class.isInstance(b))
    type = "byte";
if(int.class.isInstance(b))
    type = "int";
if(short.class.isInstance(b))
    type = "short";