I might also examine this for 8 bit signed integers, anyway here's the code.
Code: Select all
'
' ----------------------------------------------------------------------
' int_bit3.bas
'
' signed integer to binary representation
' and
' binary representation to signed integer
'
' (c) 2025 sciwiseg@gmail.com , luxan
'
' --------------------------- Declarations -----------------------------
'
declare function bit2int(a1() as ushort,isize as integer) as integer
declare sub int2bit(a as integer,a1() as ushort,isize as integer)
'
' ------------------------- Variables & arrays -------------------------
'
dim as integer a,b
dim as ushort a1(0 to 16),b1(0 to 16),i,j
'
' ----------------------------------------------------------------------
'
' Int 2 Bit
a=-15
print "a =";a
print " int 2 bit, from routine "
int2bit(a ,a1(), 16)
'
' ----------------------------- bit 2 int ------------------------------
'
b=bit2int(a1() ,16)
print " bit 2 int, from routine "
print "b =";b
'
' ------------------------ Stress testing routines ---------------------
'
' In the realm of signed 16-bit integers, the range extends
' from -32,768 to 32,767.
'
for a=-32768 to 32767
int2bit(a ,a1(), 16)
b=bit2int(a1() ,16)
if a <> b then
print " err @ ";a
exit for
end if
next a
print
print " Done "
end
'
' ======================================================================
'
'
sub int2bit(a as integer,a1() as ushort,isize as integer)
'
' Convert bits to signed integer representation .
'
dim as integer i,int_size
dim as ushort b
int_size=sizeof(a)*8-1
'print " size ";int_size
if isize<int_size then int_size=isize end if
'print " size' ";int_size
for i=0 to int_size-1
b=0
b=-Bit(a,i)
a1(i)=b
next i
'
'
end sub
'
' ----------------------------------------------------------------------
'
function bit2int(a1() as ushort,isize as integer) as integer
'
' Convert bits to signed integer representation .
'
dim as integer b,i,int_size
dim as ushort a
int_size=sizeof(b)*8-1
'print " size ";int_size
if isize<int_size then int_size=isize end if
'print " size' ";int_size
b=0
for i=0 to int_size-1
a=a1(i)
if a=1 then b=b+2^i end if
next i
' Check for negative value in two's complement if the size is 32 bits
If (a1(int_size-1) = 1) Then
' If highest bit is set, it's a negative number in two's complement
b = b - (1 Shl int_size) ' Convert to negative
End If
'
return b
'
end function
'
' ----------------------------------------------------------------------
'