Skip to content

Instantly share code, notes, and snippets.

@generalmimon
Created January 30, 2021 14:41
Show Gist options
  • Save generalmimon/be7912d570cfc5d90553418c26359ad7 to your computer and use it in GitHub Desktop.
Save generalmimon/be7912d570cfc5d90553418c26359ad7 to your computer and use it in GitHub Desktop.
A Kaitai Struct YAML specification for finding the log2 of a 32-bit integer
meta:
id: log2_int32
title: Find the log base 2 of a 32-bit integer
license: CC0-1.0
doc-ref: https://graphics.stanford.edu/~seander/bithacks.html#IntegerLog
# params:
# - id: val
# type: u4
seq:
- id: log2
type: 'log2_step(_index, _index == 0 ? val : log2[_index - 1].v, _index == 0 ? 0 : log2[_index - 1].r)'
repeat: expr
repeat-expr: _root.b.size
instances:
val:
value: 0b00000000_00011011_01011001_10111011
# ^ ^ ^ ^ ^ ^
# 31 23 20 15 7 0
result:
value: log2.last.r
b:
value: '[0xFFFF0000, 0xFF00, 0xF0, 0xC, 0x2]'
s:
value: '[16, 8, 4, 2, 1]'
types:
log2_step:
params:
- id: i
type: s4
- id: prev_v
type: u4
- id: prev_r
type: u1
instances:
v:
value: '(prev_v & _root.b[i]) != 0 ? prev_v >> _root.s[i] : prev_v'
r:
value: '(prev_v & _root.b[i]) != 0 ? prev_r | _root.s[i] : prev_r'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment