Java 如何转换';将数字补码到其2';补语是什么?
给定:字符串形式的二进制数。将其转换为2的补码形式 例如: 输入: 00000101 输出: 11111011 我知道如何将二进制数转换成1的恭维形式。但我无法转换成2补语形式 例如: 吉文斯特:111 恭维 如何编码1:将“1”添加到1的补码中,并且1+1=1 MyCodeFor 1致意:Java 如何转换';将数字补码到其2';补语是什么?,java,string,Java,String,给定:字符串形式的二进制数。将其转换为2的补码形式 例如: 输入: 00000101 输出: 11111011 我知道如何将二进制数转换成1的恭维形式。但我无法转换成2补语形式 例如: 吉文斯特:111 恭维 如何编码1:将“1”添加到1的补码中,并且1+1=1 MyCodeFor 1致意: public static String complimentDecimal(String strnew) { //Replace the 0s
public static String complimentDecimal(String strnew)
{
//Replace the 0s with 1s and 1s with 0s
StringBuilder sb = new StringBuilder();
for(int j=0;j<strnew.length();j++)
{
if(strnew.charAt(j)=='0')
sb.append("1");
else if(strnew.charAt(j)=='1')
sb.append("0");
}
String s1 = sb.toString();
}
公共静态字符串(字符串strnew)
{
//用1s替换0s,用0s替换1s
StringBuilder sb=新的StringBuilder();
对于(int j=0;j使用Integer.parseInt(,2)
您将得到二进制数的十进制形式。向其中添加一个,然后将数字转换回二进制
public static String complimentDecimal(String strnew)
{
int s2=Integer.parseInt(strnew,2);
if (s2==0)
{
String s4="1";
for(int j=0;j<strnew.length();j++)
{
s4+="0";
}
return s4;
}
else{
StringBuilder sb = new StringBuilder();
for(int j=0;j<strnew.length();j++)
{
if(strnew.charAt(j)=='0')
sb.append("1");
else if(strnew.charAt(j)=='1')
sb.append("0");
}
String s1 = sb.toString();
int s = Integer.parseInt(s1, 2);//parse int radix = 2 for binary
s++; //increment by one
return Integer.toBinaryString(s);
}
}
公共静态字符串(字符串strnew)
{
int s2=整数.parseInt(strnew,2);
如果(s2==0)
{
字符串s4=“1”;
对于(int j=0;j2s恭维形式是什么意思?2的补码显然是一种有符号的数字表示形式。此代码不适用于0。它会中断,因为它不考虑必须忽略溢出的情况。是的,但一般来说,这是实现op请求的最短方法。是的。我同意。我尝试了相同的方法。我在遇到这个例子。这里也一样,这是一个很好解决的问题,有点棘手:)好的。所以你想要零。添加零并正确地得到结果。酷:)