完全删除最重要的位

时间:2015-11-15 13:48:01

标签: c binary

我不知道如何继续这个...... 我想将存储为int 1111的二进制文件更改为存储为int的111吗?

2 个答案:

答案 0 :(得分:0)

我通常不回答" gimme teh codez"问题,但它是一个 有趣的问题,所以我做了它的乐趣。像往常一样,大部分时间都去了 进入无关的东西,如输出代码。

如果这是作业,花时间了解代码 工作,或者你只是在欺骗自己。

#include <stdio.h>
#include <string.h>

// Define "number" as an unsigned number of desired size
typedef unsigned long number;

number drop_msb(number n);
char *ntob(char *dest, number n, int min_len);

int main()
{
    number i;
    number j;
    char ibuf[65];
    char jbuf[65];

    for (i = 0; i < 512; i++) {
        j = drop_msb(i);
        ntob(ibuf, i, 0);
        ntob(jbuf, j, strlen(ibuf) - 1);
        printf("%s --> %s\n", ibuf, jbuf);
    }

    return 0;
}

number drop_msb(number n)
{
    number bit;
    number a;

    // Handle special case
    if (n == 0)
        return 0;

    // Set highest bit
    bit = ((number) -1 >> 1) ^ (number) -1;

    // Guaranteed to terminate
    while (1) {
        a = n ^ bit;
        if (a < n)
            return a;
        bit >>= 1;
    }
}

char *ntob(char *dest, number n, int min_len)
{
    /* Convert n to shortest binary string, padding with zeroes on left
     * to make it at least min_len characters long. dest should be long
     * enough to hold the maximum number, plus terminating null. */

    char *left;
    char *right;

    /* min_len should be >= 1, to handle n == 0 correctly. Also needs to
     * be non-negative to avoid bad pointer during padding. */
    if (min_len < 1)
        min_len = 1;

    // Build with lsb on left
    for (right = dest; n; right++, n >>= 1)
        *right = '0' | (n & 1);

    // Pad if needed
    while (right < dest + min_len)
        *right++ = '0';

    *right = '\0';

    // Reverse it
    for (left = dest, right--; left < right; left++, right--) {
        *left ^= *right;
        *right ^= *left;
        *left ^= *right;
    }

    return dest;
}

答案 1 :(得分:0)

unsigned int test(unsigned int n)
{
unsigned int answer = 1;

while(n>>=1 && n)
{
    answer <<= 1;
} 
answer = (answer-1);
return answer;
}

这可以解决您的问题。