I am taking an online course on Unix scripting. The topic is Unix arithmetic operators and the lesson is Logical and bitwise operations. It is not clear how much storage space Unix uses to represent integers that are typed. Bitwise negation caused me to question how many bits are used to represent numbers.
The course gives an example: ((~ 2#1001)) evaluates to 2#110
This would imply that only 4 bits are used, otherwise I would expect the example to evaluate to 2#11110110 if 8 bits were used an so on.
I do not have access to a Unix OS or this would be easy to check. I don't know if the shell matters, but I would assume BASH since it allows integers.
So, how many bits are use to represent such values? I understand Unix represents everything as strings unless declared as integer such as using typeset -i. Is this the same using something like 2#1111?
If the course says that ((~ 2#1001)) evaluates to 2#110, I wonder what shell they were using. With ksh I get:
$ typeset -i2 b
$ echo $((2#1001)) $((b=~2#1001)) $b
9 -10 -2#1010
With bash, there is no -i2 and I don't see an easy way to get binary output. I could code my own routine, but then the behavior would be whatever I decided. (But I get the "9 -10" part with bash.) Since ksh alone has a way to output binary, I did a few experiments with it. A negative number has many leading 1's while a non-negative has many leading zeros. ksh uses enough positions to output the the leftmost bit transistion. If you exceed the shell's integer size, you get undefined results, but clamping at positive or negative "infinity" (max/min integer) is common with both ksh and bash. The shells I checked have either 32 or 64 bit integers.
This has been very helpful. It reveals to me that UNIX is storing signed integer values just like most programming languages I am familiar with. The leading 1's for negative numbers would indicate that the highest order bit is a sign bit. Therefore 2#1010 is 10 and -2#1010 is -10 which would be represented as:
111....1110110 - depending on the bit size used.
Therefore I am suspecting the course is not correct when it claims ((~ 2#1001)) evaluates to 2#110, but that it actually evaluates to:
"-2#1010".
If UNIX used unsigned integers in this case then it would evaluate to a very large number depending on the bit size used. Something like 2#111...11110110. From your analysis I do not suspect this is the case.
There is one more thing I would like to verify. The course has the following question:
What do you think is the output of the following piece of code?
((x = 2#1101 & 2#110))
((y = ~x))
print - $y
The answer given is 11, as in decimal eleven or 2#1011.
From what I understand I think the answer should be -5 as in -2#101.
I plan to inform the course provider of these possible issues but I would like to make sure there is an issue. Thanks for your help.