Menu
JAQForum Ver 19.10.27

Forum Index : Microcontroller and PC projects : Non-standard length signed integers - converting to and from

Posted: 07:15am
17 Jul 2026
Copy link to clipboard
phil99
Guru


While converting a PicoMite program to a MicroMite2 found the lack of Str2Bin() and Bin2Str$() functions added quit a few lines for converting non-standard length signed integers that some sensors use. The method described in the datasheets is quite clumsy.

I recall that sometime ago Peter showed a short method of converting 24 bit signed integers to 64 bit but couldn't find it. Just knowing there is a simple way helped work it out.

These two functions should work for any length between 2 and 63 bits, not just multiples of 8 so they are also useful on any MMBasic platform. Have used them on 9 and 12 bit numbers.
The first is for converting data from sensors and the second for preparing values to be sent to them.
Function SSInt2SInt(Val%, Bits%) As Integer 'convert Short Signed Integer to Signed Integer
  SSInt2SInt = Val% - (Val% >> Bits%-1) * 2^Bits%
End Function

Function SInt2SSInt(Val%, Bits%) As Integer 'convert Signed Integer to Short Signed Integer
  SInt2SSInt = Val% And 2^Bits% -1
End Function

or
Function SSInt2SInt(Val%, Bits%) As Integer 'convert Short Signed Integer to Signed Integer
  SSInt2SInt = Val% - (Val% >> Bits%-1) * (1 << Bits%)
End Function

Function SInt2SSInt(Val%, Bits%) As Integer 'convert Signed Integer to Short Signed Integer
  SInt2SSInt = Val% And (1 << Bits%) -1
End Function
May be a shade faster, if that matters.
Edited 2026-07-20 10:03 by phil99
 


To reply to this topic, you need to log in.

The Back Shed's forum code is written, and hosted, in Australia.
© JAQ Software 2026