Xor in с linux

C++ XOR

XOR is a type of bitwise operator. The bitwise operators are the comparison operators that compare the bytes of the operand values in the binary notation. The XOR operator is the one that contains the two operands. This operation is applied to the integer value. There are almost six bitwise operators in C++.

AND operator (&), OR operator (|), XOR operator (^), Complement operator (~), shift left operator (<<), and shift right operator (>>).

Syntax of XOR

Variable 1 is the first operand on which the operation is to be performed. And variable 2 is the second operand. ‘^’ is the symbol of the XOR operator. This symbol is used between the two variables on which the XOR operation is to be applied.

C++ XOR Working

The XOR operator is the type of bitwise operator that has two operands and on each bit of these two operands, the operation of XOR is performed.

If somehow the two bits of such two operands are both zero, the resultant value returned by the XOR is zero.

The resultant is also 0 if both the values of the numbers in operands are 0.

Similarly, the result of XOR is one if and only if the two bits of two operands are 1.

Whereas the returned value is only 1 when both the bits of two operands are different. Whether the first operand is 1 and the second is zero or vice-versa.

The value of two operand values is converted into the binary value in the form of (0-1) bit. After that, we apply the XOR operation on both binary values. This binary notation is now converted into decimal form. This is the integer value similar to those values of the operands.

The Truth Table for the XOR Operator

Implementation of C++ XOR

Example 1

A simple example to explain the working of XOR in C++ is explained here. We need to have two variables that will contain two values on which we will apply the XOR function. First, the library is used in the header file to enable the use of cin and cout streams in the program that is known to be the iostream.

Now in the main program, the two variables will be initialized with the values. First, these two values will be converted into the binary notation of these numbers.

Then on each binary, the XOR operation will be applied. As we know that 1 is returned if anyone operand is 1, otherwise 0 is returned. By following these rules, the resultant of this value will be obtained. And then the binary answer will be converted into decimal notation.

The binary value of 12 is 00001100

The binary value of 25 is 00011001

Apply XOR operation on both values.

00001100
^ 00011001
_________
00010101

This is the binary value of 21 in the decimal notation.

Save the file with the extension of c and then, execute it. To execute a C++ program, we need to have a compiler of a C++ programming language. So for this purpose, a G++ compiler is used. This compiler uses an input file and displays the results. ‘-o’ is used to save the resultant in the output file.

Читайте также:  Восстановить linux через терминал

Example 2

In this example, we will find an uneven or a different value amongst the list of numbers that does not match with the other elements in the list. It is also an application of XOR that it finds the number that is different from others. A couple of numbers are provided and an odd occurring number is identified.

After using the iostream library, we have created a separate function outside the main body. This function will return the odd element in the array. This function will contain the array and the integer variable as a parameter because the variable will contain the size of the array initialized in the main program. A variable is also introduced here that will store the odd number calculated by XOR. As we know that to access each index of the array, we need to use a loop that iterates and increments in each step.

The loop will iterate till the size of an array, and in each iteration, the variable will calculate the odd number and store it.

Res ^= arr[i];
The value will be returned to the main program. In the main program, an array with some numbers is initialized. The size of the array is obtained and then a function call is made in the cout statement to display the odd number among all the same numbers.

Findodd( arr, n)
Save the above code and compile it in the terminal. You will see that the number 90 is the one that is uncommon in the whole array.

Example 3

This example is about the combined use of some bitwise operators. So after using the library, we will head towards the main program. Just like XOR, AND, and the OR operator works on two values minimum. Firstly, we will initialize two variables with the numbers. In each bitwise operation, every number will be first converted into the binary value to apply the operators, and then the results will be converted into decimal numbers, as we did in the previous example. Now, we will apply AND operator. According to this operator, both the operands must have 1 value so that the AND operator becomes true and returns 1, in the case of any 0, it will return false.

A & b;
A binary resultant value will be obtained and then the decimal conversion will be followed. The next one is the OR operator. For this bitwise operation, only a single operand must be 1, so that it can return 1, and if both operands are 1, then again 1 will be returned.

A | b;
Again, convert the binary into the decimal value. And the last operator is the XOR operator, for which we know that it returns 1 if and only if any one of its operands is 1. Otherwise, it is 0.

A ^ b;
Now, save and execute the file. You will see that each operator has worked effectively to calculate the resultant values.

Important Facts About Bitwise Operators

The bitwise operators must not be used in the place of the logical operators. Because the result of the logical operator is 1 or 0. (logical operators are AND, OR, NOT). The value that is obtained is an integer. This is because the decimal value is converted into binary value and then again, the binary is converted into a decimal value that is an integer value.

Читайте также:  Команды форматирования в линукс

Conclusion

Now, we will summarize the ‘C++ XOR’ topic. We have explained the bitwise XOR operators by defining all types. The working of XOR is also explained in the C++ programming language. Its work includes the truth table involvement that is also mentioned above. Some examples are included here to demonstrate the knowledge of the XOR bitwise operator.

About the author

Aqsa Yasin

I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.

Источник

How to perform bitwise operations on files in linux?

I wanna do some bitwise operations (for example xor two files) on files in Linux , and I have no idea how I can do that. Is there any command for that or not? any help will be appreciated.

4 Answers 4

You can map the file with mmap, apply bitwise operations on the mapped memory, and close it.

Alternatively, reading chunks into a buffer, applying the operation on the buffer, and writing out the buffer works too.

Here’s an example (C, not C++; since everything but the error handlings is the same) that inverts all bits:

#include #include #include #include #include #include int main(int argc, char* argv[]) < if (argc != 2) int fd = open(argv[1], O_RDWR); if (fd == -1) struct stat st; if (fstat(fd, &st) == -1) char* file = mmap(NULL, st.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (file == MAP_FAILED) < perror("Can't map file"); exit(4); >for (ssize_t i = 0;i < st.st_size;i++) < /* Binary operation goes here. If speed is an issue, you may want to do it on a 32 or 64 bit value at once, and handle any remaining bytes in special code. */ file[i] = ~file[i]; >munmap(file, st.st_size); close(fd); return 0; > 

@Sina I added an example program (I don’t trust my C++ skills, so I wrote it in C — you may want to C++-ify the error handling). Does this help?

@Sina First, calculate how many entries you have ( num = st.size/sizeof(entry) , where entry is int32_t or so). Cast file to a pointer to the desired type, and replace st.st_size with num in the for loop. Don’t forget to handle the remaining st.st_size — num * sizeof(entry) bytes!

@Sina You can use strtol to convert a hex string argument to a number. There’s no way to write the head of a file without completely rewriting it. You can append to a memory-mapped file .

A quick internet search revealed Monolith, a dedicated open-source program for the purpose of XORing two files. I found it because Bruce Schneier blogged about it, and the purposes of this seem to be of legal nature.

Thanks to «phihag», this code is for doing binary operations on 2 files.
Ex.1: You have two files and want to compare those two, so you do a binary XOR on those.
Ex.2: You have downloaded a file with jdownloader or sth similar and you have moved the unfinished download to another folder and then the download manager continues unfinished parts and create another file. So you have two seprate files which can completes each other. Now if you do a binary OR on these two files you have a complete file.

WARNING: The larger file will be overwritten with the the operation result.

#include #include #include #include #include #include #include int main(int argc, char* argv[]) < int FP1 = 0, FP2 = 0; struct stat St1, St2; char *File1 = NULL, *File2 = NULL; int Rn = 0; if (argc != 4) < printf("Usage: %s File1 File2 Operator\n", argv[0]); exit(1); >//Opening and mapping File1 FP1 = open(argv[1], O_RDWR); if (FP1 == -1) < perror("Error opening file1 for writing"); exit(2); >if (fstat(FP1, &St1) == -1) < perror("Can't determine file1 size"); exit(3); >File1 = (char*) mmap(NULL, St1.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, FP1, 0); if (File1 == MAP_FAILED) < perror("Can't map file1"); exit(4); >//====================== //Opening and mapping File2 FP2 = open(argv[2], O_RDWR); if (FP2 == -1) < perror("Error opening file2 for writing"); exit(2); >if (fstat(FP2, &St2) == -1) < perror("Can't determine file2 size"); exit(3); >File2 = (char*) mmap(NULL, St2.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, FP2, 0); if (File2 == MAP_FAILED) < perror("Can't map file2"); exit(4); >//====================== //Binary operations ssize_t i = 0; switch (*(argv[3])) < case '|': if (St1.st_size //====================== munmap(File1, St1.st_size); munmap(File2, St2.st_size); close(FP1); close(FP2); //Renaming the changed file and make output char Buffer[1024]; if (St1.st_size else printf("%s is mapped.\n", argv[2]); > else < Rn = system(strcat(strcat(strcat(strcat(strcpy(Buffer, "mv \""), argv[1]), "\" \""), argv[1]),"-Mapped\"")); if (Rn == -1) < perror("Unable to rename the new file."); exit(6); >else printf("%s is mapped.\n", argv[1]); > //====================== return 0; > 

Источник

XOR a file against a key

How is it possible, from bash or standard linux command-line tools, to XOR a file against a key? Something like:

cat my1GBfile | xor my1MB.key > my1GBfile.encrypted 

Off-topic: I know the encryption is quite weak with this example, but I was just wondering if this is available from bash or standard linux command-line tools (or even better: from bash and cygwin, because I use both Linux and Windows).

What exactly are you looking to do? I’m asking because XORing 1GB with 1MB is not possible. Would you like the key to be repeated until it is 1GB and then XOR?

@PawkyPenguin Yes, the key should be repeated / looped. I’m trying to do a very weak encryption (I know it, I want to test how weak it is with various tests + other things).

3 Answers 3

bash can’t deal with ASCII NUL characters, so you won’t be doing this with shell functions, you need a small program for it. This can be done in just about any language, but it seems easiest to do it in C, perhaps like this:

#include #include int main(int argc, char *argv[]) < FILE *kf; size_t ks, n, i; long pos; unsigned char *key, *buf; if (argc != 2) < fprintf (stderr, "Usage: %s \a\n", argv[0]); exit(1); > if ((kf = fopen(argv[1], "rb")) == NULL) < perror("fopen"); exit(1); >if (fseek(kf, 0L, SEEK_END)) < perror("fseek"); exit(1); >if ((pos = ftell(kf)) < 0) < perror("ftell"); exit(1); >ks = (size_t) pos; if (fseek(kf, 0L, SEEK_SET)) < perror("fseek"); exit(1); >if ((key = (unsigned char *) malloc(ks)) == NULL) < fputs("out of memory", stderr); exit(1); >if ((buf = (unsigned char *) malloc(ks)) == NULL) < fputs("out of memory", stderr); exit(1); >if (fread(key, 1, ks, kf) != ks) < perror("fread"); exit(1); >if (fclose(kf)) < perror("fclose"); exit(1); >freopen(NULL, "rb", stdin); freopen(NULL, "wb", stdout); while ((n = fread(buf, 1, ks, stdin)) != 0L) < for (i = 0; i < n; i++) buf[i] ^= key[i]; if (fwrite(buf, 1, n, stdout) != n) < perror("fwrite"); exit(1); >> free(buf); free(key); exit(0); > 

(this needs some more error checking, but oh well).

./xor my1MB.key my1GBfile.encrypted 

Источник

Оцените статью
Adblock
detector