Domanda

I have done

uint32_t bits= 0;

bits |= 1<< 31;

and then using

void printbits(uint32_t n) {
    if (n) {
        printbits(n >> 1);
        printf("%d", n & 1);
    }
}

on bits I get 10000000000000000000000000000000, which is what I want, but when I use my getbit(bits, 0)

int get_bit(int n, int bitnr) {
    int mask = 1 << bitnr;
    int masked_n = n & mask;
    int thebit = masked_n >> bitnr;
    return thebit;
}

I get a -1 instead of 1, any idea why?

Thank's!

È stato utile?

Soluzione

Right Shifting a signed number and if the number is negative is implementation behavior.

According to the Section 6.5.7 of the latest draft standard, this behavior on negative numbers is implementation dependent:

The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an 
unsigned type or if E1 has a signed type and a nonnegative value, the value of 
the result is the integral part of the quotient of E1 / 2E2. If E1 has a signed
type and a negative value, the resulting value is implementation-defined.

Edit: Please do refer, how a number is represented here https://stackoverflow.com/a/16728502/1814023

Altri suggerimenti

This does what you want.

#include <stdio.h>

void printbits(int n);
int get_bit(int n, int bitnum);

int
main()
{
    int bits = 0;

    bits |= 1 << 31;
    printbits(bits);

    bits = 0xf0f0f0f0;
    printbits(bits);  

    return(0);
}

void
printbits(int n)
{
    int j;

    for (j = 0; j < 32; j++) {
            printf("%d", get_bit(n, j));
    }
    printf("\n");
}

int
get_bit(int n, int bitnum)
{
    return((n >> (31 - bitnum)) & 1);
}

When compiled and run, it should output

10000000000000000000000000000000
11110000111100001111000011110000
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top