Home
JAQForum Ver 24.01
Log In or Join  
Active Topics
Local Time 02:43 22 Jul 2026 Privacy Policy
Jump to

Notice. New forum software under development. It's going to miss a few functions and look a bit ugly for a while, but I'm working on it full time now as the old forum was too unstable. Couple days, all good. If you notice any issues, please contact me.

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

Author Message
phil99

Guru

Joined: 11/02/2018
Location: Australia
Posts: 3321
Posted: 07:15am 17 Jul 2026
Copy link to clipboard 
Print this post

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
 
Print this page


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