The standard makes few guarantees about how these types should be represented.
It does for unsigned types.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q
Unsigned Values in Binary
A
For humans (in base ten) – Each digit can have a value of 0 .. 9 – Each digit is worth a power of 10.
Consider a (base ten) number like 3725 310^3, 710^2, 210^1, 510^0
This is called a positional number system
Computers are really good at storing on / off
Binary numbers use this store arbitrary values – We just have 2 digits, 0 (i.e., off) and 1 (on) – Place value uses powers of 2 rather than powersof ten.
Consider a binary number like 1010111 12^6, 12^5, 12^4, 12^3, 12^2, 12^1, 1*2^0
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q
Decimal to Binary
A
Given a number in base 10
How can we figure out it value in binary?
We’ll see two common ways to do this.
Each bit contributes to a sum. – Each one can be either 0 or 1. – If it’s zero, it contributes nothing to the sum. – If it’s one, it contributes a power of 2.
Try a 1 for the most significant bit. – The bit on the left.
Here, if the 26 bit was 1, the sum would be too large.
Try out a 1 for the 25 bit.
That adds 32 to the sum. – That’s less than (or equal to) 51. – … and, all the remaining bits only add up to 31. – … so the 25 bit must be a 1
That accounts for 32 of the 51 we started with – Leaving 19 (of the original 51) – … the remaining bits must add up to 19
The 24 bit is worth 16 – That doesn’t exceed the 19 we have remaining. – … and all remaining bits add up to just 15. – … so the 24 bit must be a 1.
That leaves 3 for the rest of the bits.
The 23 bit must be zero – Otherwise the sum would be too large
Likewise, the 22 bit must be zero
The 21 bit must be a 1. – It’s worth 21 = 2
That leaves just 1 for the last bit
The least significant bit must be a 1. – The one on the right.
The value of all the bits add up to 51.
This technique is called reduction of powers
How do you know what bit to start with? – Two answers – You can try out larger and larger powers of two
Until you find one that’s larger than the value you’re converting. – But, usually, you’re working with a fixed number of bits, based on the type.
E.g., an 8-bit char, a 16-bit short or a 32-bit it.