Posts

Showing posts with the label Arithmetic

Binary To Hexadecimal And Decimal In A Shell Script

Answer : It's fairly straightforward to do the conversion from binary in pure bash ( echo and printf are builtins): Binary to decimal $ echo "$((2#101010101))" 341 Binary to hexadecimal $ printf '%x\n' "$((2#101010101))" 155 Going back to binary using bash alone is somewhat more complex, so I suggest you see the other answers for solutions to that. Assuming that by binary, you mean binary data as in data with any possible byte value including 0, and not base-2 numbers: To convert from binary, od (standard), xxd (comes with vim ) or perl 's unpack come to mind. od -An -vtu1 # for decimal od -An -vtx1 # for hexadecimal xxd -p # for hexa perl -pe 'BEGIN{$\="\n";$/=\30};$_=unpack("H*",$_)' # like xxd -p # for decimal: perl -ne 'BEGIN{$\="\n";$/=\30;$,=" "}; print unpack("C*",$_)' Now, to convert back to binary, awk (standard), xxd -r or perl 's pack : ...

A Thorough Explanation On Why Division By Zero Is Undefined?

Answer : That division by zero is undefined cannot be proven without math, because it is a mathematical statement. It's like asking "How can you prove that pass interference is a foul without reference to sports?" If you have a definition of "division", then you can ask whether that definition can be applied to zero. For instance, if you define division such that x ÷ y x\div y x ÷ y means "Give the number z z z such that y ⋅ z = x y \cdot z =x y ⋅ z = x ", there is no such number in the standard real number system for y = 0 y=0 y = 0 . If we're required to have that ( x ÷ y ) ⋅ y = x (x\div y) \cdot y=x ( x ÷ y ) ⋅ y = x , then that doesn't work when y y y is equal to zero. In computer languages where x/0 returns an object for which multiplication is defined, you do not have that (x\0)*0 == x . So we can can a class of objects in which we call one of the objects "zero", and have a class method such that "division" by ...

Bash: Double Equals Vs -eq

Answer : == is a bash -specific alias for = , which performs a string (lexical) comparison instead of the -eq numeric comparison. (It's backwards from Perl: the word-style operators are numeric, the symbolic ones lexical.) To elaborate on bollovan's answer... There is no >= or <= comparison operator for strings. But you could use them with the ((...)) arithmetic command to compare integers. You can also use the other string comparison operators ( == , != , < , > , but not = ) to compare integers if you use them inside ((...)) . Examples Both [[ 01 -eq 1 ]] and (( 01 == 1 )) do integer comparisons. Both are true. Both [[ 01 == 1 ]] and [ 01 = 1 ] do string comparisons. Both are false. Both (( 01 -eq 1 )) and (( 01 = 1 )) will return an error. Note: The double bracket syntax [[...]] and the double parentheses syntax ((...)) are not supported by all shells. If you want to do integer comparison you will better use (( )), where you can a...