提问者:小点点

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


我正在使用下一个代码,它基本上将十六进制数转换为二进制形式。首先,我必须声明一个变量类型int、byte或短,然后用十六进制数对其进行inicialize,然后它必须像这样打印二进制数:

int h=0x1-

字节h=0x1-

短h=0x1-

我已经有了转换它的函数,它工作得很好,问题是我必须创建三个重载方法(一个用于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、短、字节)。


共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";