Search code examples
assemblygnu-assembler

How to use character literals in GNU GAS to replace numbers?


For example, I'd like to write something like 'a' instead of 0x61 like I can in C.

The manual mentions them at: https://sourceware.org/binutils/docs/as/Chars.html but without an example I'm not sure I understood.


Solution

  • /* Immediate. Without the `$`, does a memory access, and segfaults! */
    mov $'a, %al
    /* al == 0x61 */
    
    /* Memory. */
    mov c, %al
    /* al == 0x62 */
    
    c: .byte 'b
    
    /* Space character works. */
    mov $' , %al
    /* al == 0x20 */
    
    /* Backslash escapes work. */
    mov $'\n , %al
    /* al == 0x0A */
    

    GitHub upstream.

    There was actually an example at: https://sourceware.org/binutils/docs-2.25/as/Characters.html :

    .byte  74, 0112, 092, 0x4A, 0X4a, 'J, '\J # All the same value.
    

    I dislike this syntax for the following reasons:

    • does not play nicely with the C preprocessor: MACRO($'a) fails because cpp treats ' like a char literal.
    • may generate trailing whitespace as $', which is hard to observe
    • not C-like