Convert a decimal string to a signed 2's complement binary integer

二次信任 提交于 2020-02-07 03:41:37

问题


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.

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)

I'm using 80x86 architecture.


回答1:


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.

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.

Edit: 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 takes notting the bits, and then adding 1... but thats only if you know if its positive. If its negative you have to take 1, then not it, the reverse operation. it should be 2 cycles to do it.



来源:https://stackoverflow.com/questions/10080559/convert-a-decimal-string-to-a-signed-2s-complement-binary-integer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!