Anyone got a cheap trick to access the top or bott...
# announcements
j
Anyone got a cheap trick to access the top or bottom bytes of a short
k
val Short.leftMostByte get() = this shr 16
and
val Short.rightMostByte get() = this and 1
j
And what about mutation
Think like RAX and EAX from x86
k
Never written x86, but what about
val Short.withLeftMostByte(value: Int) get() = (this and 0x0fffffffffffffff) + ((value and 1) shl 15)
?
I hope I got that right ☺️. Obviously find a better name for the value and cast the result to Short.
j
I still need the write tho
k
Well that would be
test = test.withLeftMostByte(0)
.
j
Sorry I am lost
k
There's no way to mutate a variable from within a function, as Kotlin is pass-by value of reference.
j
Came up with a solution in the end
Copy code
class Registers {
    var A = 0
    var F = 0

    var AF
        get() = A shl 8 or F
        set(value) {
            A = value.msb()
            F = value.lsb()
        }

    var B = 0
    var C = 0
    var BC
        get() = B shl 8 or C
        set(value) {
            B = value.msb()
            C = value.lsb()
        }

    var D = 0
    var E = 0
    var DE
        get() = D shl 8 or E
        set(value) {
            D = value.msb()
            E = value.lsb()
        }

    var H = 0
    var L = 0
    var HL
        get() = H shl 8 or L
        set(value) {
            H = value.msb()
            L = value.lsb()
        }

    var SP = 0
    var PC = 0

    var ZeroFlag
        get() = F shr 6 and 1
        set(value) = when (value) {
            0 -> F = F and (1 shl 6).inv()
            1 -> F = F or (1 shl 6)
            else -> throw IllegalArgumentException("Value must be 1 or 0.")
        }

    var AddSubFlag
        get() = F shr 5 and 1
        set(value) = when(value) {
            0 -> F = F and (1 shl 5).inv()
            1 -> F = F or (1 shl 5)
            else -> throw IllegalArgumentException("Value must be 1 or 0.")
        }

    var HalfCarryFlag
        get() = F shr 4 and 1
        set(value) = when(value) {
            0 -> F = F and (1 shl 4).inv()
            1 -> F = F or (1 shl 4)
            else -> throw IllegalArgumentException("Value must be 1 or 0.")
        }

    var CarryFlag
        get() = F shr 3 and 1
        set(value) = when(value) {
            0 -> F = F and (1 shl 3).inv()
            1 -> F = F or (1 shl 3)
            else -> throw IllegalArgumentException("Value must be 1 or 0.")
        }
}