Bash script problems int to binary


Login or Register for Dates, Times and to Reply

 
Thread Tools Search this Thread
Top Forums UNIX for Beginners Questions & Answers Bash script problems int to binary
# 1  
Bash script problems int to binary

Hi, I am trying to do a bash script that convert a decimal number to a binary value, but it doesn't work...
To begin, I am just trying to convert a positive number to 8 bits binary.
Code:
read -p"Entrez un nombre entre -128 et 127 pour l'encoder en binaire: " number
binaryValues=(128 64 32 16 8 4 2 1)
binaryNumber=()
positiveNum=$number
if [ $number -lt 0 ] #transformer la copie du nombre en positif.
then
(( positiveNum=$number-$number*2 )) 
fi
for i in "${binaryValues[@]}"
do
if (( $positiveNum -ge ${binaryValues[i]} ))
then
positiveNum=$"(( $positiveNum-${binaryValues[i]} ))"
binaryNumber[i]='1';
else
binaryNumber[i]='0';
fi
done
echo ${binaryNumber[@]}

# 2  
Greetings and welcome,

Is this homework or classwork? As we have a special forum for that purpose with its own rules you have to comply with...

Q: Why have you ommited the value 0 (zero) as binary value?
# 3  
If you are using
Code:
for i in "${binaryValues[@]}"

; then i will contain the value, not the array index in every iteration
-ge is incorrect syntax within (( ... )) , that should be >=
$"((...))" is incorrect usage of quotes, that should be: $((...))
# 4  
you could write a bash function like this:

Code:
dec2bin () {
  # dec2bin num [width] [var]
  local num bin=""
  for((num=$1;num;num/=2))
  do
    bin=$((num%2))$bin
  done
  ((${#3})) &&
      printf -v ${3} "%0*d" ${2:-1} $bin ||
      printf "%0*d\n" ${2:-1} $bin
}

# example calls
dec2bin 59
dec2bin 59 8
dec2bin 23 5 test
echo 23 in binary is $test

output:
Code:
111011
00111011
23 in binary is 10111


Last edited by Chubler_XL; 11-23-2019 at 02:37 PM.. Reason: num should be a local variable to
# 5  
One wonders why if this is not homework.

How about using what's already available and set the length like this:-
Code:
#!/bin/bash

number_in=123
length=20              # Perhaps this is ridiculous, but it proves the point.

number_out=$(echo "obase=2 ; print $number_in" | bc)
printf "%0${length}d\n" "${number_out}"



I hope that this helps,
Robin
# 6  
Please be aware that



Code:
if [ $number -lt 0 ] #transformer la copie du nombre en positif.
then
(( positiveNum=$number-$number*2 )) 
fi

doesn't fly; e.g.
Code:
 127d = 01111111b
-127d = 10000001b

That's how (most) computers represent integers: two's complement.
This User Gave Thanks to RudiC For This Post:
# 7  
A quicky demo for 0 to 127 only using OSX 10.14.6, default 'bash' version 3.2.x...
Called as [./]decimal2binary.sh <integer_from_0_to_127> ...
Code:
#!/bin/bash
# decimal2binary.sh <integer_0_to_127>
NUMBER=${1}
STRING=""
for COUNT in 6 5 4 3 2 1 0
do
    M=$(( NUMBER / 2 ))
    N=$(( NUMBER % 2 ))
    NUMBER=${M}
    STRING=${STRING}$( printf "%d" "${N}" )
done
echo "0${STRING:6:1}${STRING:5:1}${STRING:4:1}${STRING:3:1}${STRING:2:1}${STRING:1:1}${STRING:0:1}"

For values -1 to -128 take a look at using binary XOR "relative to zero" for example "-1" becomes binary "11111111"
Code:
AMIGA:amiga~> XORED=$(( 00000000 ^ 11111111 ))
AMIGA:amiga~> echo "-1 = ${XORED} relative to the positive value 00000000..."
-1 = 11111111 relative to the positive value 00000000...
AMIGA:amiga~> _


Last edited by wisecracker; 11-23-2019 at 02:27 PM.. Reason: Added XOR research...
Login or Register for Dates, Times and to Reply

Previous Thread | Next Thread
Thread Tools Search this Thread
Search this Thread:
Advanced Search

Test Your Knowledge in Computers #335
Difficulty: Easy
Linus Torrent is the creator of the Linux kernel, which went on to be used in Linux, Android, and Chrome OS.
True or False?

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

sed problems - Bash Script

Hi I keep getting the following error sed: -e expression #1, char 32: unterminated `s' command sed: -e expression #1, char 35: unterminated `s' command sed: -e expression #1, char 35: unterminated `s' command whenever I use the following bash script #! /bin/bash... (2 Replies)
Discussion started by: spbr
2 Replies

2. Shell Programming and Scripting

Bash script having variable substitution problems

Hi I am setting the variables like this : setenv MODULE1 modem5__3 setenv MODULE2 modem5__2 setenv MODULE3 modem_ctrl_1_1 setenv MODULE4 modem_1_0 setenv COUNT 10 I am having a bash script as shown below ################################################ #!/bin/bash for ((... (5 Replies)
Discussion started by: kshitij
5 Replies

3. Shell Programming and Scripting

bash script error with binary operator expected.

Hello, I am not sure, where I am missing in the scirpt, I am trying to grep few users from /etc/passwd file and if exists, I added line to echo as user exist, if not create it. #!/bin/bash for vid in v707 z307 z496 z163 z292 ; do if then echo " $vid User exists " else ... (2 Replies)
Discussion started by: bobby320
2 Replies

4. Shell Programming and Scripting

Bash shell script: Str(007) to int(7),increment it(8) & convert back to string(008)

Hi, I have the following requirement. There will be following text/line in a file (eg: search-build.txt) PRODUCT_VERSION="V:01.002.007.Build1234" I need to update the incremental build number (eg here 007) every time I give a build through script. I am able to search the string and get... (4 Replies)
Discussion started by: drwatson_droid
4 Replies

5. Shell Programming and Scripting

Execution problems with BASH Shell Script

Hi I need help with my coding , first time I'm working with bash . What i must do is check if there is 3 .txt files if there is not 3 of them i must give an error code , if al three is there i must first arrange them in alphabetical order and then take the last word in al 3 of the .txt files... (1 Reply)
Discussion started by: linux newb
1 Replies

6. Shell Programming and Scripting

Execution Problems with bash script

Hello, can someone please help me to fix this script, I have a 2 files, one file has hostname information and second file has console information of the hosts in each line, I have written a script which actually reads each line in hostname file and should grep in the console file and paste the... (8 Replies)
Discussion started by: bobby320
8 Replies

7. Programming

Handle int listen(int sockfd, int backlog) in TCP

Hi, from the manual listen(2): listen for connections on socket - Linux man page It has a parameter called backlog and it limits the maximum length of queue of pending list. If I set backlog to 128, is it means no more than 128 packets can be handled by server? If I have three... (3 Replies)
Discussion started by: sehang
3 Replies

8. Shell Programming and Scripting

unzip via bash startup script problems

i have two lines in my rc.local file that are wget -O/<path>/<file>.zip url://domain.com unzip -o /<path>/<file>.zip the wget works fine, but the unzip won't work. when i copy/pase the unzip line to the prompt it works fine. i thought that maybe the unzip was running before the wget... (0 Replies)
Discussion started by: easysnowboards
0 Replies

9. UNIX for Dummies Questions & Answers

int open(const char *pathname, int flags, mode_t mode) doubt...

hello everybody! I want to create a file with permissions for read, write, and execute to everybody using C, so I write this code: #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> int main(){ int fileDescriptor; fileDescriptor =... (2 Replies)
Discussion started by: csnmgeek
2 Replies

10. Shell Programming and Scripting

Problems writing bash script to unzip files

I'm getting the following errors when I try to write a script to unzip some zip files. When I use the free trial copy of the commerical winzip program, however, they work fine. When I use -l or -t on unzip it indicates no errors. When I use the -o switch interactively from the bash command line it... (1 Reply)
Discussion started by: siegfried
1 Replies