Skip to content

Instantly share code, notes, and snippets.

@ped7g
Created March 22, 2024 19:18
Show Gist options
  • Save ped7g/27ffe953d7af00a687dd8c9d6ea7ad6c to your computer and use it in GitHub Desktop.
Save ped7g/27ffe953d7af00a687dd8c9d6ea7ad6c to your computer and use it in GitHub Desktop.
Z80 machine code challenge, turn number of bits into bytes required to store it in C language
;; original facebook post in "Z80 Assembly Programming On The ZX Spectrum" group:
; Here's a challenge for your creativity.
; Create a Z80 assembly function with the following properties:
; Input in A: values in the range [1,32]
; Output in A: 1 for 1-8, 2 for 9-16, 4 for 17-32
; No loops or other conditional jumps.
; No usage of ROM code.
; No comparisons.
; The function will map how many bits an integer needs to how many bytes it needs in a typical C style struct.
;; by Ped7g, public domain/MIT license, sjasmplus syntax:
getBytesSizeOfBits:
; A = 1..32 amount of bits ; 01..08 ; 09..10 ; 11..20
add a,$100-$11 ; F0..F7 ; F8..FF ; 00..0F c
adc a,a ; E0..EE ; F0..FE ; 00..1E|1 ; store carry, shift A left
add a,$100-$F0 ; F0..FE ; 00..0E c ; 10..2E|1
adc a,a ; E0..FC c ; 00..1C|1 ; 20..5C|2 ; store carry, shift A left
rla ; |1 ; |2 ; |4 ; store carry, shift A left
and $07 ; A = bytes ; 1 ; 2 ; 4
ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment