Actual use of Bitwise operator: -

Bhavik Vashi
2 min readOct 4, 2020

--

When I was learning a programming language, at that time I was confused about how to use Bitwise operator in the project. If you are also then let’s see the actual use of Bitwise Operator.

In a programming language, every number in a decimal number system is represented using the 8-bit binary number as following.

0: 00000000

1: 00000001

2: 00000010

3: 00000011

4: 00000100

Bitwise AND Operator (&)and Bitwise OR Operator (|): -

Bitwise AND operator takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.

Bitwise OR operator takes two numbers as operands and does OR on every bit of two numbers. The result of OR is 1 if any of the two bits is 1.

1 AND 3: 0 0 0 0 0 0 0 1 & 0 0 0 0 0 0 1 1 = 0 0 0 0 0 0 0 1

1 AND 3 = 00000001, which is equivalent to 1 in decimal number system.

1 OR 3: 0 0 0 0 0 0 0 1 | 0 0 0 0 0 0 1 1 = 0 0 0 0 0 0 1 1

1 AND 3 = 00000011, which is equivalent to 3 in decimal number system.

So now let's perform this operation in the program and check the output

let number1= 1; // equivalent to 00000001 in binary

let number2= 3; // equivalent to 00000011 in binary

console.log(“1 & 3 :”,number1&number2);

console.log(“1 | 3 :”,number1|number2);

Actual use of Bitwise operator in Project: -

Let’s consider that we want to set the permission of the file. And we reserved the 6th digit for read permission, 7th digit for write permission, 8th digit for execute permission.

So that only Read, Write and Execute permission is as follows: -

Read: 00000100 = 8

Write: 00000010 = 6

Execute: 00000001 = 1

let readPermission = 8;

let writePermission = 6;

let executePermission = 1;

//create user1 permission with no permission

let user1Permission = 0;

//assign the read and write permission to the user 1

user1Permission = user1Permission | readPermission | writePermission;

//let’s check that user1 has read permission or not

let message1= user1Permission & readPermission ? “You have read permission” : “You do not have read permission”;

console.log(message1);

//let’s check that user1 has execute permission or not

let message2= user1Permission & executePermission ? “You have execute permission” : “You do not have execute permission”;

console.log(message2);

--

--