Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 712
Sina Avatar asked Jul 31 '11 11:07

Sina


People also ask

How do you perform bitwise operations?

The bitwise AND operator ( & ) compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0. Both operands to the bitwise AND operator must have integral types.

How do you write a bitwise operator?

The Bitwise OR (|) in C: The C compiler recognizes the Bitwise OR with | operator. It takes two operands and performs the OR operation for every bit of the two operand numbers. It is also a binary operator. The output of this operator will result in 1 if any one of the two bits is 1.

Where can I find bitwise operators?

Bitwise AND Operator & The output of bitwise AND is 1 if the corresponding bits of two operands is 1. If either bit of an operand is 0, the result of corresponding bit is evaluated to 0. In C Programming, the bitwise AND operator is denoted by & . Let us suppose the bitwise AND operation of two integers 12 and 25.


1 Answers

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 <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
int main(int argc, char* argv[]) {
    if (argc != 2) {printf("Usage: %s file\n", argv[0]); exit(1);}

    int fd = open(argv[1], O_RDWR);
    if (fd == -1) {perror("Error opening file for writing"); exit(2);}

    struct stat st;
    if (fstat(fd, &st) == -1) {perror("Can't determine file size"); exit(3);}

    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;
}
like image 186
phihag Avatar answered Oct 29 '22 08:10

phihag