如何在C程序中添加按位掩码

1yjd4xko  于 2023-03-07  发布在  其他
关注(0)|答案(1)|浏览(136)

在我的任务中,我需要把一个掩码放到一个二进制系统中,我的意思是它需要改变数字是1还是0,并通过一个异或表来翻转它,我很难弄清楚如何把它应用到我的程序中。
原始代码如下:

#include <stdio.h>
#include <stdlib.h>

void banner(void) {
    int IDnumber;   // Declaration of Variable
    IDnumber = 293; // Definition (optional??)
  
    printf("########START OF BANNER###################\n");
    printf("Ian Zumbrennen, my ID number is %04d\n", IDnumber);
    printf("########END OF BANNER###################\n");
    printf("\n");
}

// printbinary()
// This function takes a signed int input and displays that value in 
// binary format to the screen with a leading '0b_'
void printbinary(unsigned int data)
{
    unsigned int n1, n2;
    
    printf("Enter first number here:\n");
    scanf("%d", &n1); 
    printf("Enter Second number here:\n");
    scanf("%d", &n2);  
    
    if ((n1 >= 0) && (n1 <= 268435456))  // Remove commas in the number range
    { 
        printf("Your numbers are %d and %d\n\n", n1, n2);
        
        if (n1 == 0) {  // Use '==' for comparison instead of '='
            printf("The first number in binary is 0\n");
        }
        else if (n1 > 0) {
            int b1[28]; //stores binary representation of 28 bit number
            int i = 0;
            
            for (; n1 > 0; n1 /= 2) {  // Use '/=' operator to divide and assign
                b1[i++] = n1 % 2; 
            }
            printf("The first number in binary is ");
            for (int j = i - 1; j >= 0; j--) {
                printf("%d", b1[j]);
            }
            printf("\n");
        }
        
        if (n2 == 0) {  // Use '==' for comparison instead of '='
            printf("The second number in binary is 0\n");
        }
        else if (n2 > 0) {
            int b2[28];
            int k = 0;
            
            for (; n2 > 0; n2 /= 2) {  // Use '/=' operator to divide and assign
                b2[k++] = n2 % 2;
            }
            printf("The second number in binary is ");
            for (int l = k - 1; l >= 0; l--) {
                printf("%d", b2[l]);
            }
            printf("\n");
        }
        else {
            printf("Number needs to be above 0 and below 268,435,456. Please try again.\n");
            return;
        }
    }
    else {
        printf("Number needs to be above 0 and below 268,435,456. Please try again.\n");
        return;
    }
}

// The variable *argv[] is an array of strings
// For example if you enter the following when running the program:
// $ ./a.exe 24 35
// 
// the value of argv[0] will be the string "./a.exe"
// the value of argv[1] will be the string "24"
// the value of argv[2] will be the string "35"
// finally the value of argv[3] will be the NULL string

void main(int argc, char *argv[])
{
    int first;
    int second;
    char menu_choice;
    
    if (argc != 3) /* argc should be 3 for correct execution */
    {
        // If the user does not enter the correct number of args
        // print info to help them use the program
        printf("Enter two numbers:\n");
        printf("usage: %s first second\n", argv[0]);
        return;
    }
    else
    {
        // No error (this else statement is optional)
        printf("Correct number of parameters entered...\n\n");
    }
    
    banner();   
    
    printf("The String value of the first entry is %s\n", argv[1]);
    printf("The String value of the second entry is %s\n", argv[2]);

    //printf("Add %d", first+second);

    first = atoi(argv[1]);
    second = atoi(argv[2]);
    
    //printf("Add %d", first+second);
    
    printf("The Numerical value of the first entry is %d\n", first);
    printf("The Numerical value of the second entry is %d\n\n", second);

    printf("First shifted left one bit is %d\n", first << 1);
    printf("First shifted right one bit is is %d\n\n", first >> 1);
    
    printf("Binary version of FIRST\n");
    printbinary(first);
    printf("\n#########\n\n");
    printf("Binary version of SECOND\n");
    printbinary(second);
    printf("\n#########\n\n");

    // Now add a user interface that prompts the user and gets new info
    while (1) {
        printf("Choose a MATH operation\n");
        printf("1 - Addition, 2 - Subtraction, 3 - Multiplication, 0 - quit\n");
        
        // Input using getchar()
        //menu_choice = getchar();
        //getchar();        // Do a second getchar to get rid of the CARRIAGE RETURN

        //Alternate using gets()
        //gets(&menu_choice);
        //printf("Operation = %c\n", menu_choice);
        
        // Preferred method of run-time input using scanf()
        // Read choice from user
        scanf(" %c", &menu_choice);
        
        // scanf() can be used to input multiple values
        //scanf(" %c %d %d", &op, &var1, &var2);
        //printf("First = %d, Second = %d\n", var1, var2);
                
        switch (menu_choice) {
          case '1':
            printf("\nFirst plus second = %d\n\n", first + second);
            break;
            
          case '2':
            printf("\nFirst minus second = %d\n\n", first - second);
            break;
            
          case '3':
            printf("\nFirst times second = %d\n\n", first * second);
            break;
            
          case '0':
            return;
          case 'f':
            printf("\nEnter a new value for the variable first\n");
            scanf(" %d", &first);
            printf("\nThe new value you entered is %d\n\n", first);
            break;

          default:
            printf("Unknown choice, Try Again\n\n");
        }
    }
}

我试着将代码行更改为以下代码行,但它似乎不是我想要的。是否有办法修复代码,以便它可以修复此问题?
先谢谢你。

void printbinary(unsigned int data, unsigned int mask) {
    if (data == 0) {
        printf("The number in binary is 0\n");
        return;
    }

    int bits[32];
    int i = 0;

    for (; data > 0; data /= 2) {
        bits[i++] = data % 2;
    }

    printf("The number in binary is %d\n", i);

    for (int j = i - 1; j >= 0; j--) {
        if (mask & (1 << j)) {
            printf("0");
        } else if (mask & 1 == j) {
            printf("1");
        } else {
            printf("%d", bits[j]);
        }
    }

    printf("\n");
}
tkclm6bt

tkclm6bt1#

我建议不要在循环中使用/= 2,而是使用〉〉= 1,因为整数除法涉及到舍入。除非你确定你的标准的舍入模式适合你的目的,否则我会切换到逐位移位。
语句“if(mask & 1 ==j)”在我看来很奇怪,因为它只对最低的2位(j=0,j=1)产生true,这是故意的吗?
您是否希望执行以下操作:
//如果掩码在此位位置为1,则翻转位
如果(掩码&(1〈〈j)!= 0)比特[j]=1-比特[j];

相关问题