繁体   English   中英

负数如何存储在内存中? 如何知道位表示?

[英]How negative numbers are stored in memory? How to know the bit representation?

我知道MSB,LSB,符号和幅度的一,二的补码等。现在,我想知道我是否正在编写和编程进行某些位操作的代码,如何检查内存中的实际位级别数据?

int a = -1; 我怎么知道4位表示是1001还是11101111

如何找出实现中用于表示负数的方法?

我正在寻找某种方法来检查C程序的位级数据。

我当前的平台是Ubuntu 12.04 LTS。 再一次,问题不在于如何完成。 它是关于如何找出或证明它是以某种方式完成的。

union { int i; unsigned u; } x;
x.i = -1;

现在, xu为您提供了具有相同位的无符号整数。 只有一种表示无符号数字的方法,因此您可以进行检查。 (提示:这很可能是二进制补码。)

printf("%x\n", x.u);

上面的print语句将打印出无符号整数的十六进制表示形式,您可以使用它来确定位。

通过应用按位运算。 例如,您可以通过执行a & (1<<n)来测试是否设置了第n位(将其应用于循环中,然后得到整数)。

编辑:但这仅在内部表示形式为二进制时有效。 如果使用不同的系统(例如,俄国人在70年代使用的是具有三元逻辑和数字系统的计算机,而波兰语则是基于负数的系统)将无法提供正确的内部使用格式。

一种简单的方法是在调试器中检查变量,如下所示:

(gdb) p/t var

p/t表示打印二进制表示形式。

void showBit(int num, int nBit)//nBit -> number of bits
{
    unsigned int temp = 1<<(nBit-1), i;

    for(i=0; i<nBit; ++i)
    {
        printf("%d ", ((num&temp)?1:0) );
        temp = temp>>1;
    }
    printf("\n");
}  

您可以使用此功能来打印二进制表示形式。 ideone上看到它。

在C语言中,带负号的数字以2的补码格式表示。

这样做是为了避免使用任何编译器(即使int是8位或16位或32位,依此类推,它也可以工作)。

在您的情况下,如果编译器将int解释为8位,则将存储1111 1111。 当第一个位(符号位)为1时,编译器就会知道这是一个负数,并且知道该数必须是两位的补码。 就是0000 0001,带负号

您甚至可以使用union

union num
{
    int f;
    char c[4];
};

void printBinary(union num u)
{
    int i,t,j;

    for(i=sizeof(u)-1; i>=0; i--)
    {
            for(j=0,t=128; j<8; j++,t>>=1)
                    printf("%d",(u.c[i]&t)?1:0);
            printf(" ");
    }
}

int main() 
{
    union num n;
    n.f=10;
    printBinary(n);
    return 0;
}

看到这里: http : //ideone.com/i9YCt

如何找出实现中用于表示负数的方法?

方法如下:

unsigned int a = -1;
swicth (a & 3U)
{
    case 3:
        printf("two's complement\n");
        break;

    case 2:
        printf("one's complement\n");
        break;

    case 1:
        printf("sign and magnitude\n");
        break;

    default:
        printf("compiler broken\n");
        break; 
}

最终的答案实际上是在您的编译器文档中,该文档必须记录使用哪种签名表示。 例如,对于gcc

有符号整数类型是使用符号和大小,二进制补码还是一个二进制补码表示的,以及非常值是陷阱表示形式还是普通值表示(C99 6.2.6.2)

GCC仅支持二进制补码类型,所有位模式均为普通值

http://gcc.gnu.org/onlinedocs/gcc/Integers-implementation.html

正数和负数由数字的第8位标识。 如果第8位为0,则为正,否则为负。

For example x=8
so In binary x=8=0000 1000 (It is positive number, so eight bit is 0 from right to left)

For negative x = -8
The negative numbers are represented in binary using 2's complement usually.
 so x = -8 

step 1 binary of        8 = 0000 1000
step 2 1's complement     = 1111 0111
step 3 2's complement     =         1
                         y = 1111 1000 =248(so it represents the negative because 8th bit is 1 then it follows the below formula)

The formula for getting negative value from binary representation is 2^8-y
 so 256-248=8

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM