LoginLogin
Nintendo shutting down 3DS + Wii U online services, see our post

Looking for Two's Compliment Rule in SmileBasic Integers...

Root / Programming Questions / [.]

CoinzReturnsCreated:
So I'm trying to confirm that I can use the two's compliment rule to tell that a negative number is negative by checking the bits of it's four bytes. I'm assuming a four byte value to allow for up to 32 bit integers stored... So yeah here we go this is the code.
CLS
COLOR #TWHITE
DIM BYTES[20]

@AGAIN
INPUT "ENTER A VALUE " , VALUE
GETBYTES VALUE, 4
PRINT "BYTE 0 IS " +STR$(BYTES[0])
PRINT "BYTE 1 IS " +STR$(BYTES[1])
PRINT "BYTE 2 IS " +STR$(BYTES[2])
PRINT "BYTE 3 IS " +STR$(BYTES[3])
FOR T=0 TO 3
COLOR #TOLIVE
PRINT "GETTING BITS OF BYTE # " +STR$(T)

BYTESTRING$ =" "
FOR S=0 TO 7 ' 8 BITS PER BYTE
BYTESTRING$ = BYTESTRING$ +STR$(CHECKBIT(BYTES[T], S)
NEXT
COLOR #TGREEN
PRINT BYTESTRING$

GOTO @AGAIN

DEF GETBYTES NUM, LENGTH ' LENGTH IN THIS CASE IS THE NUMBER OF BYTES WE EXPECTED
FOR I =0 TO LENGTH
BYTES[I] = (NUM AND 255)
NUM = (NUM - (NUM AND 255)/256
NEXT I
END

DEF CHECKBITS(N, I)
IF (N AND (1 <<I) ) THEN
RETURN TRUE
ELSE
RETURN FALSE
ENDIF
END
So there you have it. Now it seems to work fine but I noticed... there's no pattern when you input a negative value that gaurentees if it's negative that the leading bit will be one.

assuming that the first bit of 255 is 1 I can perform addition using the two's compliment rule on 8 bit integers like so:
PRINT (255 + (6 AND 255) ) AND 255 'OUTPUTS 05

You're printing the bits in reverse order. Bit 7 is the leftmost bit in a byte, and bit 0 is the rightmost bit.
' 76543210
&B11011101
That said, there's already a built-in way to print a number in binary:
PRINT BIN$(123)
PRINT BIN$(123,8) 'Zero-padded
EDIT: Fixed the zero-padded example

assuming that the first bit of 255 is 1 I can perform addition using the two's compliment rule on 8 bit integers like so:
PRINT (255 + (6 AND 255) ) AND 255 'OUTPUTS 05
You can just do A+B AND &HFF
You're printing the bits in reverse order. Bit 7 is the leftmost bit in a byte, and bit 0 is the rightmost bit.
' 76543210
&B11011101
That said, there's already a built-in way to print a number in binary:
PRINT BIN$(123)
PRINT FORMAT$("%08B",123) 'Zero-padded
BIN$(number,length) uses 0 padding, unlike STR$

BIN$(number,length) uses 0 padding, unlike STR$
Oh, I missed that entirely. I don't usually use languages with optional parameters, so I didn't even consider the possibility that it had one, hence I never checked the help for it.