I was told bytes in assembly are counted by the byte of machine code. Is that true? If so what steps should be taken to correctly get bytes?
Machine code and assembly are different languages
If you write a program in assembly, therefore, you can submit it two different ways: you can either submit the source code you enter into the assembler (an assembly language solution), or else submit the object code or executable that you get out of the assembler (a machine code solution). The header of your post would be, e.g., "x86 assembly (
gas)" or "x86 machine code (Linux)" in the two cases.
Machine code solutions should typically come with a disassembly in order to make them easier to read, although that isn't technically speaking required.
Note that except on DOS (where the .COM file format has very little boilerplate), it's probably going to make more sense to submit a function rather than a full program due to the vast difference in boilerplate amount. In this case, you only have to submit the machine code for the function itself (including the
ret or equivalent at the end!), rather than an entire object file.
Assembly languages are scored by the compiled/assembled size
For example, take this x86 program to reverse the bit order of a number:
xor eax, eax inc eax myloop: shr ecx, 1 adc eax, eax jnc short myloop
This compiles into:
33 C0 40 D1 E9 13 C0 73 FA
(a series of hex bytes)
Thus, this is 9 bytes.
Another example, in a different assembly dialect:
# reverse bits of a 32 bit word .text .globl rbit .type rbit,@function rbit: push $32 # prepare loop counter pop %ecx 0: shrl 4(%esp) # shift lsb of argument into carry flag adc %eax,%eax # shift carry flag into lsb loop 0b # decrement %ecx and jump until ecx = 0 ret # return
This compiles/assembles to these 12 hex bytes:
6a 20 59 d1 6c 24 04 11 c0 e2 f8 c3
So to get your score, simply compile/assemble the assembly and get the size of the resulting file.
On Mac, this can be done as follows: (different flags may be needed for different assembly dialects)
test.asm is the file containing the assembly (not compiled/assembled though), then run this:
nasm -f elf test.asm
This makes an object file. Next, run either:
ld test.o -o test
gcc test.o -o test
Then you can run
./test. Which of
gcc depends on the format of the assembly. If it has a
main function, use
gcc. If it has a defined start point, use
No. The correct way to count bytes is to count the length of the source file.
xor eax, eax
is 12 bytes. Assembly is no different to any other source-based language in this regard.
Whatever is shorter.
What about all other compiled languages? Should C/C++ be scored by binary output size? Java/Kotlin/other JVM languages by bytecode size?
Languages are defined by their interpreter, compiling should be considered a middle step.