신혜성
신혜성

Reputation: 1

How to express '\n' in Assembly?

I would like to express '\n' as an Assembly code!!

For example,

#include <stdio.h>

int main() {
    printf("Hi! My name is Joe.\n I'm 11 years old");

    return 0;
}

How to express '\n' part in Assembly?

Upvotes: 0

Views: 1362

Answers (3)

Peter Cordes
Peter Cordes

Reputation: 365862

In NASM syntax, C-style escapes are processed inside backticks, so you can write `\n` as an integer constant with value 0xa = 10

mov byte [mem], `\n`

newline: equ `\n`        ; or 0xa or 10, but not '\n' or "\n"

str1: db `Hello\n`
str2: db 'Hello', 0xa   ; exactly identical to str1

See the manual.

For the GNU assembler, see its manual: '\n' works, like movb $'\n', (%rdi)

Upvotes: 1

Dietrich Epp
Dietrich Epp

Reputation: 213827

This depends on the particular assembler you are using, but in some (including GAS: https://sourceware.org/binutils/docs/as/Characters.html), it is still \n, just like C. You can see what the assembly looks like in a number of different ways, but these days GodBolt is pretty nice.

https://gcc.godbolt.org/z/ZLq3Kn

.LC0:
        .string "Hi! My name is Joe.\n I'm 11 years old"

You can see that the string looks the same. In GAS, .string creates a 0-terminated string. If you change to Clang (which uses the same syntax but makes different choices about which directives to emit), you'll see it uses .asciz.

.L.str:
        .asciz  "Hi! My name is Joe.\n I'm 11 years old"

But in both assemblers, \n is the same.

Not all assemblers support this syntax. But many do. Check the manual for your assembler.

.string is the same as .asciz on most targets, both appending a zero. The manual says that in GAS syntax for some ISAs, .string might not append a zero, while .asciz always does and .ascii never does. The z stands for zero.

Upvotes: 3

Febriyanto Nugroho
Febriyanto Nugroho

Reputation: 563

To express \n in assembler, especially nasm assembler (pointing comment from dvhh) you can use 0x0a.

Example :

string1 db "Hi! My name is Joe.", 0x0a
string2 db "I'm 11 years old.", 0x0a

Upvotes: 2

Related Questions