Thread: ASM function

  1. #1
    Registered User
    Join Date
    Mar 2019
    Posts
    7

    ASM function

    Hello,

    my task is to create following function:

    Code:
    unsigned char nthbyte_x(unsigned char n, unsigned long x) {
       __asm {
          ...
       }
    }
    Its result should be the value of nth byte in number x. Could you give me some basic explanation of how should I do that, or some commands, I should use? Thank you.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    37,485
    return ( x >> (8*n) ) & 0xff;
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Feb 2019
    Posts
    533
    I like to deal with asm, as any optimization junkie does, but keep in mind that programming directly in asm will restrict your code to a specific family of processors.

    For example, the Salem's code, for x86 in i686 mode will compile as:
    Code:
    nthbyte_x:
      movzx ecx, BYTE [esp+4]
      mov eax, [esp+8]
      sal ecx, 3
      shr eax, cl
      ret
    But on x86 in amd64 mode, it will be:
    Code:
    nthbyte_x:
      movzx edi, dil
      mov rax, rsi
      lea ecx, [rdi*8]
      shr rax, cl
      ret
    And on ARM (AArch32, for Cortex-A53):
    Code:
    nthbyte_x:
      lsl r0, r0, #3
      lsr r0, r1, r0
      uxtb  r0, r0
      bx  lr
    But on ARM (AArch64, for Cortex-A53):
    Code:
    nthbyte_x:
      ubfiz w0, w0, 3, 8
      lsr x0, x1, x0
      ret
    And, to cite GCC example, there are other 55 (see GCC documetation) "kinds" of assembly.

    So, using asm your code is not portable... If you want to restrict your implementation to one of them, it is ok to use asm, if not DON'T USE IT!

  4. #4
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,859
    Quote Originally Posted by flp1969
    So, using asm your code is not portable... If you want to restrict your implementation to one of them, it is ok to use asm, if not DON'T USE IT!
    *like*
    Fact - Beethoven wrote his first symphony in C

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Function Prototype, Function Call, and Function definition
    By dmcarpenter in forum C Programming
    Replies: 9
    Last Post: 04-09-2013, 03:29 AM
  2. Replies: 11
    Last Post: 09-07-2012, 04:35 AM
  3. Replies: 13
    Last Post: 03-20-2012, 08:29 AM
  4. Print function: sending a function.. through a function?
    By scarlet00014 in forum C Programming
    Replies: 3
    Last Post: 11-05-2008, 05:03 PM
  5. Replies: 9
    Last Post: 01-02-2007, 04:22 PM

Tags for this Thread