十进制数的二进制补码

时间:2015-05-05 11:01:50

标签: shell decimal twos-complement

我想使用shell找到二进制数的二进制补码。 有人可以帮帮我吗?

2 个答案:

答案 0 :(得分:0)

两个补码以二进制方式工作,因此根据您的数字位数,您可以处理十进制数字,如:

if number >= pow(2, N - 1)
    return number
else
    return number - pow(2, N)

示例:

N = 3
number = 2
number is less than pow(2, 3 - 1) = 4, so result = number = 2

N = 3
number = 6
number is greater than pow(2, 3 - 1) = 4, so result = number - pow(2, 4) = 6 - 8 = -2

我从Wikipedia

接受了这个想法

<强> BASH

#!/bin/bash

NUMBER="$1"
BITS="$2"

# I check the presence of the arguments
if [ -z "$NUMBER" -o -z "$BITS" ]; then
    echo "Usage: $0 <number> <n_bits>"
    exit
fi

# I check the arguments are numeric values
RE='^[0-9]+$'
if ! [[ $NUMBER =~ $RE ]] || ! [[ $BITS =~ $RE ]] ; then
    echo "The inputs must be numeric values"
    exit
fi

# Calculate, with awk, the powers I need
N_POW=$(awk "BEGIN{ print 2 ** $BITS }")
NM1_POW=$(awk "BEGIN{ print 2 ** ($BITS - 1) }")

# Result...
if [ $NUMBER -lt $NM1_POW ];
then
    echo $NUMBER
else
    echo $(($NUMBER - $N_POW))
fi

答案 1 :(得分:0)

您可以尝试使用bc:

dec=-4; bits=6;
bin=$(printf "%0.${bits}d\n" $(echo "ibase=10;obase=2;$(((2**(bits))+$dec))" | bc) )
bin=$(echo $bin | grep -oE "[[:digit:]]{$bits}$")
echo $bin
111100