0

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?

신혜성
  • 1
  • 1
  • 1
    the [same way](https://godbolt.org/z/PBC6R3), or alternatively you can use its ASCII code `0x0A` – dvhh Oct 08 '19 at 02:43
  • If you are looking for an answer related to a processor emulator, most probably [this should help](https://stackoverflow.com/questions/8374034/newline-in-8086-assembly-language-my-text-prints-stair-stepped): – Kavitha Karunakaran Oct 08 '19 at 02:46
  • Which assembler do you use? What architecture are you programming for? – fuz Oct 08 '19 at 09:58

3 Answers3

3

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.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
2

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
  • and in in some assemblers you can continue the string on the same line. – Erik Eidt Oct 08 '19 at 03:15
  • Note that these strings do *not* have a 0 terminator. For that, append a `,0` to `db`'s list of byte elements, after the `0xa` or `\`\n\``. (NASM but not YASM supports C-style escapes inside backticks) – Peter Cordes Oct 08 '19 at 04:54
1

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)

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847