[ / / / / / / / / / / / / / ] [ dir / animu / ausneets / cafechan / hkon9 / hkpol / komica / vg / vichan ][Options][ watchlist ]

/prog/ - Programming

Programming board
You can now write text to your AI-generated image at https://aiproto.com It is currently free to use for Proto members.
Name
Email
Subject
Comment *
Password (Randomized for file and post deletion; you may also set your own.)
* = required field[▶ Show post options & limits]
Confused? See the FAQ.
Expand all images

File (hide): 6581dec1904855b⋯.png (510.83 KB, 640x763, 640:763, bernd on date.png) (h) (u)

[–]

55f7b6 (2) No.5101>>5130 [Watch Thread][Show All Posts]

Negative numbers in signed binary = bizarro world.

def toBinary(num, length=8):
'''Convert a decimal number to a signed binary number of given length.'''
capacity = 2 ** length
assert type(num) == int and -capacity / 2 <= num < capacity / 2

bits = ['0'] * length
n = (capacity + num) % capacity
i = length - 1

while i >= 0 and n > 0:
bits[i] = str(n % 2)
n //= 2
i -= 1

return ''.join(bits)

for i in range(-8, 8):
print('{0:2}: {1:4}'.format(i, toBinary(i)))

-8: 11111000
-7: 11111001
-6: 11111010
-5: 11111011
-4: 11111100
-3: 11111101
-2: 11111110
-1: 11111111
0: 00000000
1: 00000001
2: 00000010
3: 00000011
4: 00000100
5: 00000101
6: 00000110
7: 00000111

55f7b6 (2) No.5102

In 1-bit signed binary 0 = 0 and 1 = -1.


2cac77 (1) No.5113

Two's complement representation, you dummy: https://en.wikipedia.org/wiki/Two%27s_complement


2f1474 (1) No.5130

>>5101 (OP)

ez



#include<bits/stdc++.h>
using namespace std;

int main() {
for (int i = -8; i < 8; i++)
cout << setw(2) << i << ":" << bitset<8>(i).to_string() << endl;
return 0;
}

// Output
// -8:11111000
// -7:11111001
// -6:11111010
// -5:11111011
// -4:11111100
// -3:11111101
// -2:11111110
// -1:11111111
// 0:00000000
// 1:00000001
// 2:00000010
// 3:00000011
// 4:00000100
// 5:00000101
// 6:00000110
// 7:00000111


0a5d49 (1) No.5150

How is it bizarro? Just imagine there is a 9th 'sign' digit. It makes perfect sense that 11111111 + 1 = 00000000




[Return][Go to top][Catalog][Screencap][Nerve Center][Cancer][Update] ( Scroll to new posts) ( Auto) 5
4 replies | 0 images | 4 UIDs | Page ?
[Post a Reply]
[ / / / / / / / / / / / / / ] [ dir / animu / ausneets / cafechan / hkon9 / hkpol / komica / vg / vichan ][ watchlist ]