The MASM Forum

General => The Campus => Topic started by: fearless on August 30, 2023, 06:17:23 AM

Title: x64 abs() function
Post by: fearless on August 30, 2023, 06:17:23 AM
Came across this post online for a x86 version of abs() function - https://helloacm.com/optimized-abs-function-in-assembly/

cdq
xor eax, edx
sub eax, edx

Just wondering if anyone knows the equivalent in x64 asm?


Title: Re: x64 abs() function
Post by: jj2007 on August 30, 2023, 06:43:23 AM
  mov rax, -1234567890123456789
  cqo
  xor rax, rdx
  sub rax, rdx
Title: Re: x64 abs() function
Post by: fearless on August 30, 2023, 06:48:44 AM
Thanks JJ
Title: Re: x64 abs() function
Post by: Caché GB on August 30, 2023, 12:58:04 PM
Here are a few techniques for finding the absolute |u| of a real4 and real8 value in assembly language.

_fabsf(val) for real4 / float
.data

  align 16
  g_XMAbsMaskps              oword  07FFFFFFF7FFFFFFF7FFFFFFF7FFFFFFFh

.code

     local  absfVal:real4

          movss  xmm0, FLT4(-19.2345)

            mov  eax, 80000000h
           movd  xmm1, eax
         shufps  xmm1, xmm1, 0
         andnps  xmm1, xmm0
          movss  absfVal, xmm1              ; _fabsf(val)

; or

          movss  xmm0, FLT4(-28.2345)

            mov  eax, 07FFFFFFFh
           movd  xmm1, eax
         shufps  xmm1, xmm1, 0
          andps  xmm1, xmm0
          movss  absfVal, xmm1              ; _fabsf(val)

; or even better

          movss  xmm0, FLT4(-37.2345)

          andps  xmm0, g_XMAbsMaskps        ; "align 16" g_XMAbsMaskps oword  07FFFFFFF7FFFFFFF7FFFFFFF7FFFFFFFh
          movss  absfVal, xmm0              ; _fabsf(val)


 _fabs(val) for real8 / double
.data

  align 16
  g_XMabsMaskpd              oword  07FFFFFFFFFFFFFFF7FFFFFFFFFFFFFFFh

.code

     local  absdVal:real8

           movd  xmm0, FLT8(-46.2345)

            mov  rax, 08000000000000000h
           movd  xmm1, rax
         pshufd  xmm1, xmm1, 01000100y ; 044h
         andnps  xmm1, xmm0
           movd  absdVal, xmm1              ; _fabs(val)

; or

           movd  xmm0, FLT8(-55.2345)

            mov  rax, 07FFFFFFFFFFFFFFFh
           movd  xmm1, rax
         pshufd  xmm1, xmm1, 01000100y ; 044h
          andps  xmm1, xmm0
           movd  absdVal, xmm1              ; _fabs(val)

; or even better

           movd  xmm0, FLT8(-64.2345)

          andps  xmm0, g_XMabsMaskpd        ; "align 16" g_XMabsMaskpd oword  07FFFFFFFFFFFFFFF7FFFFFFFFFFFFFFFh
           movd  absdVal, xmm0              ; _fabs(val)

Title: Re: x64 abs() function
Post by: Caché GB on August 30, 2023, 01:18:42 PM
And yes thanks JJ. learnt another mnemonic,  cqo - convert qword to oword (x64 only)