AmirSina Mashayekh
AmirSina Mashayekh

Reputation: 520

Join two bytes in BASCOM-AVR

How can I join two bytes to make an 16-bit int variable in BASCOM-AVR?

Upvotes: 1

Views: 964

Answers (4)

Coder
Coder

Reputation: 1

I use Bascom-Avr.

There is another way: using overlay. Basically you define 2 bytes and one Integer, but it is possible to assign the same memory space for the two variables. Even share to bytes array.

Example:

Dim mBytes(2) As Byte
Dim mLsb As Byte At mBytes(1) Overlay
                           
Dim mMsb As Byte At mBytes(2) Overlay

Dim Rd As Integer At mBytes(1) Overlay

Then, you can access mBytes as array, or mLsb and mMsb as components of Rd, or directly the Rd variable.

It only is matter of the order of mLsb and mMsb (little/big endian).

As memory is shared, that's do the trick. It is faster than shifting or doing the arithmetic...

Upvotes: 0

AmirSina Mashayekh
AmirSina Mashayekh

Reputation: 520

You can find this in BASCOM index:

varn = MAKEINT(LSB , MSB)

The equivalent code is:

varn = (256 * MSB) + LSB
  • Varn: Variable that will be assigned with the converted value.
  • LSB: Variable or constant with the LS Byte.
  • MSB: Variable or constant with the MS Byte.

For example:

varn = MAKEINT(&B00100010,&B11101101)

The result is &B1110110100100010.

Upvotes: 0

eoredson
eoredson

Reputation: 1165

Function to shift-left/right binary:

Byte1# = 255
PRINT HEX$(Byte1#)
Byte1# = SHL(Byte1#, 8) ' shift-left 8 bits
PRINT HEX$(Byte1#)
END
' function to shift-left binary bits
FUNCTION SHL (V#, X)
    SHL = V# * 2 ^ X
END FUNCTION
' function to shift-right binary bits
FUNCTION SHR (V#, X)
    SHR = V# / 2 ^ X
END FUNCTION

Upvotes: 1

Jeff Zeitlin
Jeff Zeitlin

Reputation: 10809

PARTIAL ANSWER:

Subquestion 1

If one byte is stored in the variable BYTE1 and the other is stored in the variable BYTE2, you can merge them into WORD1 in many BASICS with WORD1 = BYTE1: WORD1 = (WORD1 SHL 8) OR BYTE2. This makes BYTE1 into the high-order bits of WORD1, and BYTE2 into the low-order bits.

Subquestion 2

If you want to mask (or select) specific bits of a word, use the AND operator, summing up the bit values of the bits of interest - for example, if you want to select the first and third bits (counting the first bit as the LSB of the word) of the variable FLAGS, you would look at the value of FLAGS AND 5 - 5 is binary 0000000000000101, so you are guaranteeing that all bits in the result will be 0 except for the first and third, which will carry whatever value they are showing in FLAGS (this is 'bitwise AND').

Upvotes: 2

Related Questions