将两个字节char byte1和char byte2连接成一个short

问题描述

我想在组装中将两个字节char byte1char byte2连接成单个short

我该怎么办?使用班次?

我正在使用IA32

解决方法

我只是解决了这个问题,并在有人遇到相同问题的情况下这样做:

concatBytes.s:

 .section .data

.global byte1
.global byte2

.section .text
.global concatBytes


concatBytes:

#prologue 
    pushl %ebp 
    movl %esp,%ebp
    
    pushl %ebx
    
#body of the function

    movl $0,%eax
    movb byte1,%al
    movb byte2,%ah
    

    
#epilogue

    popl %ebx
    
    movl %ebp,%esp
    popl %ebp
    ret

,

main.c

#include <stdio.h> 
#include "concatBytes.h" 
char byte1 = '11101010'; 
char byte2 = '10100001'; 
int main()
{ 
    short result = 0; 
    result = concatBytes(); 
    printf("Result = %hd",result); 
    return 0;
}

concatBytes.h

short concatBytes(void);

concatBytes.c

extern char byte1; 
extern char byte2;
short concatBytes(void)
{
    return(((short)byte1)^((short)byte2));
}

很明显:

gcc main.c concatBytes.c -o main
main.c:3:14: warning: character constant too long for its type
 char byte1 = '11101010'; 
              ^
main.c:3:14: warning: overflow in implicit constant conversion [-Woverflow]
main.c:4:14: warning: character constant too long for its type
 char byte2 = '10100001'; 
              ^
main.c:4:14: warning: overflow in implicit constant conversion [-Woverflow]

这是错误的语法。所以这引出了一个问题,你是说这个意思吗?

#include <stdio.h> 
#include "concatBytes.h" 
char byte1[] = "11101010"; 
char byte2[] = "10100001"; 
int main()
{ 
    short result = 0; 
    result = concatBytes(); 
    printf("Result = %hd",result); 
    return 0;
}

或者这个:

#include <stdio.h> 
#include "concatBytes.h" 
char byte1 = 0xEA; 
char byte2 = 0xA1; 
int main()
{ 
    short result = 0; 
    result = concatBytes(); 
    printf("Result = %hd",result); 
    return 0;
}

假设后者:

0000000000400559 <concatBytes>:
  400559:   55                      push   %rbp
  40055a:   48 89 e5                mov    %rsp,%rbp
  40055d:   0f b6 15 d4 0a 20 00    movzbl 0x200ad4(%rip),%edx        # 601038 <byte1>
  400564:   0f b6 05 ce 0a 20 00    movzbl 0x200ace(%rip),%eax        # 601039 <byte2>
  40056b:   31 d0                   xor    %edx,%eax
  40056d:   66 98                   cbtw   
  40056f:   5d                      pop    %rbp
  400570:   c3                      retq   

这使您大致了解调用约定,然后只需用“连接”替换该代码的中间部分

如果它是一个字符串,那么您首先需要将每个字符串转换为一个字节,然后进行连接。您可以轻松地找出其中一个...