invert case. A simple demonstration of combining an Assembly module into a C++ program.

by Michael Calkins (Login MCalkins)
ASM Forum

 
================================
invcasetest.cpp
================================
#include <stdio.h>

extern "C" unsigned int invertcase(char * const p);    // note: the pointer is const. the string is not const.

int main () {
 char t[] = "Hello, World!";
 printf("char count: %u\n", invertcase(t));
 puts(t);
 return 0;
}
================================


================================
invcasefunc.asm
================================
global _invertcase
extern _puts

section .text          ; read only, executable

; call with: on the stack: pointer to null terminated string.
; extern "C" unsigned int invertcase(char * const p);    // note: the pointer is const. the string is not const.
; that is, the function modifies the string, but not the pointer at [ebp+8]

_invertcase:
push ebp               ; create stack frame
mov ebp,esp
push esi
push edi
pushf                  ; because I'm clearing the direction flag

push howdy
call _puts             ; demonstrating calling C standard lib from assembly.
add esp,4

cld
mov esi,[ebp+8]        ; access stack parameter
mov edi,esi
xor ecx,ecx

.loop:
lodsb
test al,al             ; null terminator
jz .done
cmp al,'A'
jb .skip
cmp al,'z'
ja .skip
cmp al,'Z'
jbe .doit
cmp al,'a'
jb .skip
.doit:
xor al,0x20            ; invert case
.skip:
stosb
inc ecx
jmp .loop

.done:
mov eax,ecx            ; return value
popf
pop edi
pop esi
pop ebp                ; destroy stack frame
ret

; returns: eax = character count. destroys: ecx. preserves: esi, edi, flags.

section .rdata         ; read only, data

howdy: db "Howdy from inside the assembly module.",0
================================


build instructions:

nasm -f win32 -o invcasefunc.o invcasefunc.asm
\qb64\internal\c\c_compiler\bin\g++ -O3 -s -Wall invcasetest.cpp invcasefunc.o -o invcasetest.exe

output:

Howdy from inside the assembly module.
char count: 13
hELLO, wORLD!


notes:

extern "C"
means that the function uses C instead of C++ name mangling. C name mangling is standardized on x86, but C++ name mangling is not (MinGW and MSVC++ use different styles).
The function will be __cdecl by default. This means that it leaves the parameter on the stack, and the caller is expected to remove it.

Regards,
Michael



    
This message has been edited by MCalkins on Mar 12, 2017 6:39 PM

Posted on Mar 12, 2017, 6:36 PM

Respond to this message   

Return to Index

Response TitleAuthor and Date
question: xor with 32mn on Mar 12, 7:06 PM
 Re: question: xor with 32Michael Calkins on Mar 12, 7:22 PM
  *of course. thanks mcmn on Mar 12, 7:28 PM

 Copyright © 1999-2017 Network54. All rights reserved.   Terms of Use   Privacy Statement  

Quantcast