如何以编程方式在Java中获取二进制数的2的补码

时间:2017-03-04 12:22:09

标签: java binary twos-complement

如何计算Android / Java中Hex值的2的补码。

    For Example : 
    String x = 10011010;
    1's complement of x = 01100101;
    2's complement is 01100110;

我如何用Java语言实现?

我曾尝试使用以下代码将二进制文件转换为其赞美内容:

public String complementFunction(String bin) {
        String  ones = "";

        for (int i = 0; i < bin.length(); i++) {
            ones += flip(bin.charAt(i));
        }
        return ones;
    }

// Returns '0' for '1' and '1' for '0'
    public char flip(char c) {
        return (c == '0') ? '1' : '0';
    }

但我无法得到它的两个补充。

3 个答案:

答案 0 :(得分:2)

感谢大家的帮助。 我得到了解决方案,如下:

  public String twosCompliment(String bin) {
        String twos = "", ones = "";

        for (int i = 0; i < bin.length(); i++) {
            ones += flip(bin.charAt(i));
        }
        int number0 = Integer.parseInt(ones, 2);
        StringBuilder builder = new StringBuilder(ones);
        boolean b = false;
        for (int i = ones.length() - 1; i > 0; i--) {
            if (ones.charAt(i) == '1') {
                builder.setCharAt(i, '0');
            } else {
                builder.setCharAt(i, '1');
                b = true;
                break;
            }
        }
        if (!b)
            builder.append("1", 0, 7);

        twos = builder.toString();

        return twos;
    }

// Returns '0' for '1' and '1' for '0'
    public char flip(char c) {
        return (c == '0') ? '1' : '0';
    }

感谢所有人的帮助。

答案 1 :(得分:1)

This wikipedia section解释了一个简单的方法来获得2的补码:得到1的补码,然后加1(用二进制逻辑)。因此,您可以使用已有的complementFunction,然后向后浏览字符串。如果您找到1,请将其翻转并继续。如果您找到0,请将其翻转并停止。

String  twos = "";
for (int i = bin.length() - 1; i >= 0; i--) {
    if (bin.charAt(i) == '1') {
        twos = "0" + twos;
    } else {
        twos = bin.substring(0, i) + "1" + two;
        break;
    }
    twos = flip(bin.charAt(i));
}
return twos;

答案 2 :(得分:0)

上面的

@BackSlash的评论很有趣。答案是基于此思想编写的完整程序:

import java.time.temporal.ValueRange;
import java.util.Scanner;

//This program generates convert decimal to binary
public class ConvertDecimalToBinary {


    public static int getNumberOfBytes(int n) {
        int bytes = 0;
        ValueRange byteRange = ValueRange.of(Byte.MIN_VALUE, Byte.MAX_VALUE);
        ValueRange shortRange = ValueRange.of(Short.MIN_VALUE, Short.MAX_VALUE);
        ValueRange intRange = ValueRange.of(Integer.MIN_VALUE, Integer.MAX_VALUE);
        if (byteRange.isValidValue(n)) {
            bytes = 1;
        } else if (shortRange.isValidValue(n)) {
            bytes = 2;
        } else if (intRange.isValidValue(n)) {
            bytes = 4;
        }
        return bytes;
    }

    //Convert a positive decimal number to binary
    public static String convertPositiveNumberToBinary(int n, int bytes,boolean reverse) {
        int bits = 8 * bytes;
        StringBuilder sb = new StringBuilder(bits); //in-bits
        if (n == 0) {
            sb.append("0");
        } else {
            while (n > 0) {
                sb.append(n % 2);
                n >>= 1;  //aka n/2
            }
        }

        if (sb.length() < bits) {
            for (int i = sb.length(); i < bits; i++) {
                sb.append("0");

            }
        }
        if (reverse) {
            return sb.toString();
        } else {
            return sb.reverse().toString();
        }
    }

    //Convert negative decimal number to binary
    public static String convertNegativeNumberToBinary(int n, int bytes) {
        int m = -n; //conver to positve
        String binary = convertPositiveNumberToBinary(m,bytes,true);
        int len = binary.length();
        StringBuilder sb = new StringBuilder(len); //in-bits
        boolean foundFirstOne = false;
        for(int i=0; i < len;i++) {
            if(foundFirstOne)  {
                if(binary.charAt(i) == '1') {
                    sb.append('0');
                }
                else {
                    sb.append('1');
                }
            }
            else {
                if(binary.charAt(i) == '1') {
                    foundFirstOne = true;
                }
                sb.append(binary.charAt(i));
            }
        }
        return sb.reverse().toString();

    }
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while(scanner.hasNextInt()) {
            int n = scanner.nextInt();
            int bytes = getNumberOfBytes(n);
            String binary;

            if(n >= 0) {
                binary = convertPositiveNumberToBinary(n,bytes,false);
            }
            else {
                binary = convertNegativeNumberToBinary(n,bytes);
            }
            System.out.println(String.format("Binary representation of {%s} is {%s}",n,binary));
        }
        scanner.close();
    }
}