Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if nth bit is set in bash

Tags:

bash

binary

awk

I'm wondering if there's a way to replace the if statement with something that checks whether $2 has the 7th bit set to 1?

cat $file | awk '{if ($2 == 87) print $1; else {}}' > out.txt"

For instance, 93 should print something whereas 128 should not.

like image 987
jyu429 Avatar asked Jul 02 '15 08:07

jyu429


1 Answers

bash has bitwise operators

Test 7th bit:

$ echo $(((93 & 0x40) != 0))
1

$ echo $(((128 & 0x40) != 0))
0

See also the bash documentation

Though if you're parsing the values out of a file, you're probably better off continuing to use awk, as the answer of @RakholiyaJenish

like image 128
nos Avatar answered Nov 03 '22 01:11

nos