LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   vim script, converting decimal to binary, 8 bit output (https://www.linuxquestions.org/questions/linux-newbie-8/vim-script-converting-decimal-to-binary-8-bit-output-770065/)

adament1978 11-18-2009 05:37 PM

vim script, converting decimal to binary, 8 bit output
 
Hello, I'm very much a newb to linux scripts. This is no longer just an attempt to help out a fellow class mate, this is really bugging me about how to do this correctly, or intelligently.

The task was this, create a vim script that converts a decimal number to binary. The output must be in 8bit format 00000000

I figured out how to get the conversion with something like this:
n=0
bin=0
echo -n "Input decimal number to convert : "
read n
bin=`echo "obase=2;ibase=10; $n" | bc`
echo "$n is equivalent \"$bin\" in Binary"

This is mishmash of another script I found for converting hex, but I got it to work for binary.
Things I don't know: why n=0 and why bin=0,where and how to limit the output to 8 bits.
The only references we have available: internet and man pages, no book material is available to us.

The only thing I could find that might allow for an 8bit output had to do with perhaps setting the length of the output to 8; ( length 8) but I never got anything to work correctly. The guy I was trying to help ended up adding 256 lines to get it to work right, but I believe this defeats the purpose of the script, which is to make things easier. I would really appreciate anyone thoughts on this matter, as I would really like to see how it should work, thank you.

Tinkster 11-18-2009 05:46 PM

Hi,

Welcome to LQ!

The only way to achieve the desired limitation is to
reject input > 255.


Cheers,
Tink

chrism01 11-18-2009 08:29 PM

Quote:

why n=0 and why bin=0
That's just being cautious by initializing vars to zero before use. Not strictly required if you know they will be written to before being used.


All times are GMT -5. The time now is 04:03 PM.