如何将二进制补码二进制字符串转换为负十进制数?

时间:2016-05-05 19:17:07

标签: java binary twos-complement negative-number

我试图找到一种快速/简单的方法将二进制补码二进制字符串转换为负十进制数。我试图使用this question中提供的方法,但它不起作用。这是我试图运行的代码:

try {
  define('JPATH_BASE', "../");
  define( 'DS', DIRECTORY_SEPARATOR );

  require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
  require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );

  require ('libraries/joomla/factory.php');
  # require_once '../class.phpmailer.php';

  $name=$_REQUEST['name']; 
  $subject=$_REQUEST['subject'];
  $body=$_REQUEST['body']; 
  $from=$_REQUEST['from'];

  $to = "mymail@me.com";;

  # Invoke JMail Class
  $mail = JFactory::getMailer();
  # $mail->isSMTP; is not working

  # Set sender array so that my name will show up neatly in your inbox
  $sender = array($user, $name);
  $mail->setSender($sender);

  # Add a recipient
  $mail->addRecipient($to);
  $mail->ClearCCs();
  $mail->ClearBCCs();

  $mail->setSubject($subject);
  $mail->setBody($body);

  $mail->ClearAttachments();
  $mail->ClearCustomHeaders();

  # Send once you have set all of your options
  $mail->Send();
  echo json_encode(array('status' => 'success','message'=>"Message Sent OK"));
}
catch (Exception $e) {
  echo json_encode(array('status' => 'failed','message'=>$e->getMessage()));
}

当我运行此代码时,结果为9。 我错过了什么吗? 我做错了什么?

2 个答案:

答案 0 :(得分:1)

Two's Complement algorithm,之后,我写了以下内容:

public static int getTwosComplement(String binaryInt) {
    //Check if the number is negative.
    //We know it's negative if it starts with a 1
    if (binaryInt.charAt(0) == '1') {
        //Call our invert digits method
        String invertedInt = invertDigits(binaryInt);
        //Change this to decimal format.
        int decimalValue = Integer.parseInt(invertedInt, 2);
        //Add 1 to the curernt decimal and multiply it by -1
        //because we know it's a negative number
        decimalValue = (decimalValue + 1) * -1;
        //return the final result
        return decimalValue;
    } else {
        //Else we know it's a positive number, so just convert
        //the number to decimal base.
        return Integer.parseInt(binaryInt, 2);
    }
}

public static String invertDigits(String binaryInt) {
    String result = binaryInt;
    result = result.replace("0", " "); //temp replace 0s
    result = result.replace("1", "0"); //replace 1s with 0s
    result = result.replace(" ", "1"); //put the 1s back in
    return result;
}

以下是一些示例运行:

  

运行:
  两个补充:1000:-8
  两个补充:1001:-7
  二的补充:1010:-6
  二的补充:0000:0
  二的补充:0001:1
  二的补充:0111:7

答案 1 :(得分:0)

  

当我运行此代码时,结果是9。

应该如此。

  

我错过了什么吗?我做错了什么?

您的代码与您引用的答案之间的差异是输入中的位数。没有指定宽度,“两个补码”没有明确定义。您复制的答案是16位二进制补码,因为Java short是16位宽。如果你想要4位二进制补码,那么没有相应的Java数据类型,所以你将无法使用相同的快捷方式。