#! /usr/bin/python3
# ===================================================================
# play/test byte and bytearry
# ===================================================================
#
# From: www.masswerk.at/6502/6502_instruction_set.html
#
# 16-bit address words are little endian, lo(w)-byte first,
# followed by the hi(gh)-byte. (An assembler will use a human
# readable, big-endian notation as in $HHLL.)
#
# The available 16-bit address space is conceived as consisting
# of pages of 256 bytes each, with address hi-bytes represententing
# the page index. An increment with carry may affect the hi-byte
# and may thus result in a crossing of page boundaries, adding
# an extra cycle to the execution.
# Increments without carry do not affect the hi-byte of an address
# and no page transitions do occur. Generally, increments of
# 16-bit addresses include a carry, increments of zeropage
# addresses don't.
# Notably this is not related in any way to the state of the
# carry bit of the accumulator.
#
# Branch offsets are signed 8-bit values, -128 ... +127,
# negative offsets in two's complement. Page transitions may
# occur and add an extra cycle to the exucution.
#
# ===================================================================
# -------------------------------------------------------------------
# ---- functions
# -------------------------------------------------------------------
# ---- create a byte from two nibbles
def create_byte_from_nibbles(n1,n2):
return((n1 & 0xF) << 4) | (n2 & 0xF)
# ---- convert an int to bit string
def bit_string(n,minlen=8):
lsb = n & 0xFF # least significant byte
return f'0b{lsb:0{minlen}b}'
# ---- convert an int to hex string
def hex_string(n,minlen=8):
return f'0x{n:0{minlen}X}'
# ---- display byte array
def display_array(a):
i = 0
for b in a:
xx = hex_string(b,2)
bb = bit_string(b)
print(f'[{i:4}] {b:3} {xx} {bb}')
i = i + 1
# ---- convert int to two bytes
def convert_int_to_two_bytes(n):
b2 = bytearray(2)
b2[0] = n & 0xFF
b2[1] = (n >> 8) & 0xFF
return b2
# ---- convert two bytes to int
def convert_two_bytes_to_int(b2):
return int.from_bytes(b2,byteorder='little')
# -------------------------------------------------------------------
# ---- main
# -------------------------------------------------------------------
if __name__ == '__main__':
print()
print('---- bytearray ---------------------------------')
ary = bytearray(8)
ary[0] = 255
ary[2] = 0
ary[2] = 32
ary[3] = 0x44
ary[4] = 0b101
ary[7] = 1
display_array(ary)
print()
print('---- int to two byte; two bytes to int ---------')
def test_b2(n):
print(f'------ test {n}')
b2 = convert_int_to_two_bytes(n)
display_array(b2)
n = convert_two_bytes_to_int(b2)
print(f'int is {n}')
test_b2(43)
test_b2(-43)
test_b2(23456)
test_b2(-1)
test_b2(1234567)
test_b2(0xFFFFFFFF)
print()
print('---- 0xABCD ------------------------------------')
test_b2(0xABCD)