N
N
Nikc77772021-06-20 00:05:59
C++ / C#
Nikc7777, 2021-06-20 00:05:59

How to apply the bitwise NOT operation in practice?

We enter two strings with a binary representation, then print the results of applying the "~" operation to each number. The task is solved, only through if else, but the "~" operator was not applied. This operator applies to integers. To data types int, short, char, can it be applied directly to the bits of these types.
Here is the code:

#include <stdio.h>
#include <stdlib.h>
#define BITS 8

char bin_inv(unsigned char *s);

int main(void){
   unsigned char val_1[BITS];
   unsigned char val_2[BITS];
   
   printf("Enter binary number: ");
   scanf("%s %s", val_1, val_2);
   bin_inv(val_1);
   bin_inv(val_2);
   printf("Inverted binary number: %s %s\n", val_1, val_2);
 return 0;
}
char bin_inv(unsigned char *s){
  char i;
    for(i = 0; i < sizeof(char) * BITS && s[i]; ++i){
       if(s[i]) == '0')
          s[i] = '1';
        else
           s[i] = '0';}
   return *s;
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
LoliDeveloper, 2021-06-20
@LoliDeveloper

In general, it is possible to fill chars in the bin_inv (uchar * s) function through bit masks and apply NOT to them. And just as well to read back.
You will save memory, but because of the time masks, it will work longer.
Why not as an alternative.

N
none7, 2021-06-20
@none7

s[i] = '0'+((~(s[i]-'0'))&1);
But NOT far-fetched here, everyone usually uses XOR.
*((*long long)s) ^= 0x0101010101010101LL;
And no cycle is needed.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question