1

I tried conversion using BIN=$(echo "obase=2; ibase=16; $i" | bc ). My output is example 1000000100000011110000110000010. I need work (check by view) with eleventh bit from end. I need my output format as (ex): 1000 0010 0000 1111......

Can ask for help? Thanks

2 Answers 2

1

Use a Ruby One-Liner

If you just want to split your binary into 4-digit chunks, you can use any language that understands the {} interval operator. Your mileage may vary with sed and awk, but perl and ruby always support the operator.

There are certainly other ways to do the same thing, but some are more readable than others. Ruby provides a very clean and maintainable syntax for this sort of string operation.

Code

BIN=1000000100000011110000110000010
echo "$BIN" | ruby -ne 'puts $_.scan(/\d{4}/).join " "'

Output

1000 0001 0000 0011 1100 0011 0000
Sign up to request clarification or add additional context in comments.

Comments

1

Use following command to print $BIN in chunks of 4

format=`echo %0$(((${#BIN}%4 ? ${#BIN}/4 + 1 : ${#BIN}/4) * 4))d`
printf $format $BIN | sed 's/.\{4\}/& /g'

In the first line, we calculate the length of the output binary value using

${#BIN}

Then in the same line we form the format specifier.

For eg.,

0101 - %04d
1 - %04d
10010 - %08d

Using the format specifier obtained in $format, printf prints the binary value prefixed with 0 to make the string length multiple of 4.

The 'sed' command then divides the string into chunks of 4.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.