NASM: little-endian WORD constant

60 views Asked by At

I want to make WORD variable in little endian without manually converting it, for example:

SECTION .data
    variable1: dw 2  ; <-- How to make 2 little-endian without manually writing db 0x02, 0x00?

Maybe NASM has builtin macro or you can suggest your one?

1

There are 1 answers

0
Peter Cordes On BEST ANSWER

x86 is little-endian so dw 2 already does assemble the same as db 2, 0.

To assemble big-endian integers, you just need to swap the bytes. For a 2-byte x86 word, that's simple, just rotate by 8, which we can do with a NASM single-line macro and arithmetic expression

; mask before right shifting because NASM expressions are 64-bit integers
; and we don't want to shift in ones from negative numbers 
%define  swap_word(x)  ( (x<<8) | ((x&0xFFFF)>>>8) )

(...) & 0xffff isn't needed, NASM doesn't warn about truncation even without. It would make a difference if used like dd swap_word(-2) (FF FE FF FF instead of FF FE 00 00)

NASM listing from some uses (nasm -l /dev/stdout foo.asm), with spaces put between the bytes because even though it's dumping individual bytes, it by default crams them together like 0002 which is confusing in this case when we're messing around with big-endian data:

  00 02                    dw swap_word(2)
  FF FE                    dw swap_word(-2)
  00 02                    dw 0x0200
  FF FE                    dw 0xFEFF         ; same thing done manually