Welcome Guest, you are in: Login

Fruit Of The Shed

Navigation (MMBasic)






Search the wiki

»


Page History: Sign Extend an Integer

Compare Page Revisions



« Older Revision - Back to Page History - Current Revision


Page Revision: 2018/01/31 22:45


Often times, a number may not be the same width as an Integer variable, e.g. a register might be in two's-compliment form but only byte-wide. An example here is the temperature register (&H11) of the popular DS3231 RTC chip.

If this number is placed directly in an integer variable without sign extending (in this case, the seventh bit) through to the end of the integer (bit 63) the temperature will be incorrect if negative - it will read over 128C. So in the case of the DS3231, it is necessary to extend bit 7 of the register through the remaining 56 bits to obtain a true 64-bit integer value of the reading that will play nicely with the rest of your code... Of course this isn't necessary if you are not expecting sub-zero temperatures and want to take the chance.

The following function will return a value sign-extended from any given bit. There is no error checking - if you feed it rubbish or try to crash it you'll probably succeed.

Syntax:
=SExt(Bit,Value)

Examples:
Print Bin$(SExt(7,&h7f),64)

0000000000000000000000000000000000000000000000000000000001111111
^ bit 7

Print Bin$(SExt(7,&h8f),64)

1111111111111111111111111111111111111111111111111111111110001111
^ bit 7


RTC GetReg 17,x
Temp=SExt(7,x)


Code:
	Function SExt(b As Integer,v As Integer) As Integer' sign extend bit b of value v
		If v And 2^b Then 'extend 1
			SExt=v Or (-1 << (b+1))
		Else 'extend 0
			SExt= v And ((2^(b+1))-1)
		EndIf
	End Function