0

所以我正在读取用户的 8 位输入,并将其保存到一个变量中。例如:

输入一个 8 位十六进制数:1ABC5678

所以,然后我循环遍历 1ABC5678 十六进制数,从数字 0-9 中减去 48,从 AF 中减去 55,以获得输入的数字表示。但这似乎是错误的。我的目标是将 8 位十六进制转换为八进制。我已经知道如何从二进制转换为八进制,那就是通过屏蔽和移动 32 位二进制数字。但我的问题是我获取二进制文件的方法是错误的。

我在英特尔 IA-32 上编码。x86。

更新数据

现在我得到了一个 32 位二进制变量名二进制文件。我想将其转换为八进制。关于如何移动 3by3 以获得正确的八进制数的任何想法?

到目前为止,这是我的代码:

; Now we have the Binary digits saved into the binary variable
; Lets convert into octal

octal_init:
mov     ecx, 11             ; initialize count
mov     edi, octal             ; point to start of new string
mov     eax, [binary]               ; get a character
MOV     edx, 00000000000000000000000000000000b ;Clear EDX

octal_cont:
MOV     dl, al
SHL     dl, 5
SHR     dl, 5

octal_top:
mov     [edi], dl               ; store char in new string
inc     edi                     ; update dest pointer
SHR     eax, 3
dec     ecx                     ; update char count
jnz     octal_cont                  ; loop to top if more chars
4

2 回答 2

0

其中一些问题是:

  • 输入字符串是换行符终止的,而不是空值终止的
  • 一些逻辑错误

你可以这样写:

L1_init:
mov     ecx, 8                  ; initialize count
mov     esi, buf                ; point to start of buffer
mov     edi, binary             ; point to start of new string


L1_top:
mov     al, [esi]               ; get a character
inc     esi                     ; update source pointer

cmp       al, '0'               ; Compare al with ascii '0'
...
or        dl, al                           ; Merge in the four bits just computed
loop      L1_top                          ; Loop back for next byte to convert

mov     [edi], edx               ; store char in new string

L1_end:

请注意,您已经检查过您有 8 个字符,因此无需在循环中再次执行此操作。

于 2012-10-16T05:13:06.417 回答
-1

将 Hex 字符串转换为 int 值的最简单方法是使用 strtol()、strtoll() 或 strtoimax():

#include <inttypes.h>
#include <stdlib.h>

intmax_t     max;
long         l;
long long    ll;
const char * str = "1ABC5678";

max = strtoimax(str, NULL, 16);
l   = strtol(str, NULL, 16);
ll  = strtoll(str, NULL, 16);

或者,如果您愿意,也可以手动编写代码:

int          pos;
long         l;
const char * str = "1ABC5678";

l = 0;
for(pos = 0; str[pos]; pos++)
{
    l = l << 4; // each Hex digit represents 4 bits

    // convert ASCII characters to int value
    if ((str[pos] >= '0') && (str[pos] <= '9'))
       l += (str[pos] - '0') & 0x0F;
    else if ((str[pos] >= 'A') && (str[pos] <= 'F'))
       l += (str[pos] - 'A' + 10) & 0x0F;
    else if ((str[pos] >= 'a') && (str[pos] <= 'f'))
       l += (str[pos] - 'a' + 10) 0x0F;
};
于 2012-10-15T17:37:45.890 回答