将十进制字符串转换为带符号的2的补码二进制整数 [英] Convert a decimal string to a signed 2's complement binary integer

查看:139
本文介绍了将十进制字符串转换为带符号的2的补码二进制整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道将十进制整数(由用户输入)转换为内存中2的恭维表示的代码是什么.

I was just wondering what the code would be to convert a decimal integer (entered in by the user) to a 2's compliment representation in memory.

示例:用户输入1234作为小数.我想将04D2(二进制2的补码表示形式)存储在AX中(因为仅允许使用字长字符串)

Example: the user enters 1234 as the decimal. I want to store 04D2 (the binary 2's complement representation) in AX (since I'm only allowed to use word length strings)

我正在使用80x86架构.

I'm using 80x86 architecture.

推荐答案

将数字字符串转换为整数通常非常简单:一次读取一个数字,然后将其转换为十进制数字(通常通过减去'0 ' 从中).您将现有值乘以十,然后加上当前数字的值.

Converting a string of digits to an integer is mostly fairly simple: you read one digit at a time, convert that to a decimal number (normally by subtracting '0' from it). You take your existing value, multiply it by ten, and add the value of the current digit.

处理负数只会增加一点难度.大多数人通过保留一个标志来表示该数字是否为负(如果以'-'开头).然后,当他们转换完数字后,如果设置了该标志,他们将否定.

Dealing with negative numbers adds just a bit more difficulty to that. Most people do it by keeping a flag to indicate the number is negative if it starts with a '-'. Then, when they've converted the number, they negate if if that flag is set.

但是,这确实存在一个问题:转换最负数会花费一些额外的工作,因为(以2的补码形式)最负数的幅度大于您可以表示为正数的幅度(不使用更多位) .例如,16位2的补码范围为-32768到+32767,但是您(至少)需要17位或16位无符号数字来表示+32768.

That does, however, have one problem: converting the most negative number takes some extra work, because (in 2's complement) the most negative number has a larger magnitude than you can represent as a positive number (without using more bits). For example, 16-bit 2's complement numbers range from -32768 to +32767, but you need either (at least) 17 bits or an unsigned 16-bit number to represent +32768.

将十进制数字转换为整数后,需要将整数转换为十六进制数字以十六进制显示.这种转换要容易一些.您反复除以16,其余的将成为下一个十六进制数字.通常,您将使用"0123456789abcdef"之类的表,并使用该余数索引该表以获取要显示的数字.您重复除法并使用余数,直到分红为零.一个窍门是,它会按 reverse 的顺序生成数字(从最低到最高),因此通常将它们放入缓冲区,从缓冲区的末尾开始,一直到开头

Once you've converted the decimal digits to an integer, you'll need to convert the integer to hexadecimal digits to display it in hex. That conversion is a little bit easier. You repeatedly divide by 16 and the remainder becomes the next hexadecimal digit. You'll normally use a table like "0123456789abcdef" and use that remainder to index into the table to get the digit for display. You repeat the division and using the remainder until your dividend is zero. The one trick is that this produces the digits in reverse order (from least to most significant), so you normally put them into a buffer, starting from the end of the buffer and working your way toward the beginning.

这篇关于将十进制字符串转换为带符号的2的补码二进制整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆