如何在C中创建一个作为按位补码运算符的函数 [英] How do I create a function which works as a bitwise complement operator in C

查看:85
本文介绍了如何在C中创建一个作为按位补码运算符的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被指派创建一个作为按位补码运算符的函数。到目前为止,我创建的是:



I have been assigned to create a function which works as the bitwise complement operator. So far what I have created is this:

#include <stdio.h>

/**
    print the binary equivalent of a signed integer value.

*/

void printBinary(int n){
    int i;
    unsigned k = 1 << 31;
    for(i = 0; i < sizeof(int) * 8; ++i){
        if ((n & (k >> i)) == (k >> i))
            printf("1");
        else
            printf("0");

        if ( (i+1) % 8 == 0)
            printf(" ");
    }
    putchar('\n');
}


/**
 The function flip receives a signed integer n and inverts every bit of n and
 returns the inverted integer. That is, it performs equivalent to bitwise complement
 operator ~.
 You must not use ~ for doing the function.
 You must not change the prototype of function flip.
 You must not change anywhere else of the program apart from developing function flip.

*/

int flip(int n){
    // Your code starts here
	
	int i;
	unsigned int a = 1 << 31;
	
	printBinary(n);
	for(i=0; i< sizeof(int) * 8; i++)
	{
		if(n & (a >> i))
			n = n & (0 >> i);
		else 
			n = n | (1 >> i);
	}
	printBinary(n);
	
    return n;
}

int main(){
    // Do not change anything here.
    // There are 3 test cases, you need to pass through all of them.
    // Run the program after completing flip function.

    int k = 5;
    int p = flip(k);
    int count = 0;
    if (p == -6){
        printf("First Test case: Passed\n");
        count++;
    }
    else{
        printf("First Test case: Failed\n");
    }

    p = flip(-1);
    if (p == 0){

        printf("Second Test case: Passed\n");
        count++;
    }
    else{
        printf("Second Test case: Failed\n");
    }

    p = flip(100);
    if (p == -101){
        printf("Third Test case: Passed\n");
        count++;
    }
    else{
        printf("Third Test case: Failed\n");
    }

    // checking if all test cases were passed.
    if (count == 3){
        printf("Well done\n");
    }
    else{
        printf("%d out of 3 test cases are passed\n", count);
        printf("Please recheck your function, you are missing something\n");
    }



    return 0;
}







在我尝试过的翻转功能中。该功能可正常工作以翻转1位,但不会翻转0位。我无法得到它。我使用了bitwise&和|运营商。



我的尝试:



我认为可能是if else条件语句的缺陷所以我尝试使用if else if梯形图但它不起作用。




In the flip function I have tried to do it. The function works correctly for flipping the 1 bits but it isn't flipping the 0 bits. I am not able to get it. I have used the bitwise & and | operator.

What I have tried:

I thought it might be the defect of the if else conditional statement so I tried using if else if ladder but it is not working.

推荐答案

我喜欢编写可以一般工作的函数这就是我要做的。我会写一个函数来测试一个字节的位,一个用来设置一个位,一个用来清除一点。



测试一下的一般策略是将值1移位到指定的位位置,然后检查移位位和字节之间的二进制AND运算结果。设置一个位非常相似 - 将一个移位到正确的位置并将其与字节移位。清除一点有点不同:移位,补移移位值,然后用字节对它进行AND。



你可以通过使用你可以做你需要的这三个功能。如果设置了一个位然后将其清除,如果它已清除则设置它。现在对字节中的每个位执行此操作。你可能已经注意到我一直在指字节。那是因为如果您可以为一个字节执行此操作,那么您可以根据需要为多个字节执行此操作。只需告诉它你传递了多少字节或一次一个地传递给函数。
I like to write functions that can work generically so that is what I would do. I would write one function to test a bit in a byte, one to set a bit, and one to clear a bit.

The general tactic to test a bit is to shift the value 1 to the specified bit position and then check the result of the binary AND operation between the shifted bit and the byte. To set a bit is very similar - shift a one to the right place and OR it with the byte. Clearing a bit is a little different : shift the bit, complement the shifted value, and then AND it with the byte.

You can do what you need to by using these three functions. If a bit is set then clear it and if it is clear then set it. Now do this for every bit in the byte. You might have noticed that I keep referring to bytes. That is because if you can do this for one byte then you can do it for as many bytes as you want. Just tell it how many bytes you passed or pass them to the function one at a time.


void print_binary( int n )
{
  const int BITS = sizeof(int)*8; // bit count of int variable
  const unsigned MSB = (1 << (sizeof(int)*8-1)); // this is most significant bit
  int i;
  for (i = 0; i < BITS; ++i)
  {
    char c = (n & MSB) ? '1' : '0';
    putchar(c);
    n <<= 1;
  }
  putchar('\n');
}


int flip(int n)
{
  print_binary(n);
  int flipped = (n ^ -1); // the integer representation of -1 has all bits set
  print_binary(flipped);
  return flipped;
}


你的功能失败,因为这一行

Your function fail because this line
n = n & (0 >> i);



只是删除 n

要按照你尝试的方式清除1位,你需要使用not操作:


is just erasing n.
To clear 1 bit the way you try, you need to use the not operation:

n = n & ( ~ (1 >> i));





但是使用xor操作,您的代码可以简化为:



But with the xor operation, your code can be simplified to:

for(i=0; i< sizeof(int) * 8; i++)
{
    if(n & (a >> i))
        n = n & (0 >> i);
    else
        n = n | (1 >> i);
    n = n ^ (1 >> i);
}



按位运算可以同时改变所有位,不能进一步简化代码到1行:


Bitwise operations can change all bits at same time, the not can further simplify the code to 1 line:

n = ~ n; // flips all bits





C中的按位操作 - 维基百科 [ ^ ]


这篇关于如何在C中创建一个作为按位补码运算符的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆