如何将字符串中的数字转换为汇编中的任何基数?
如何将字符串中包含的数字从任何基数转换为任何其他基数?
基数可以是任何数字,即:2、16、10、4、8、9。
我希望用户输入基数。用户将输入输出基数(要转换为的基数)。用户将输入他想要转换的数字。
预想: 我将把输入基数和输出基数保存在变量中。然后我将把他输入的数字保存在字符串中(因为他可以输入任何类型的数字(十六进制、二进制、基数 5..)。
我只是想弄清楚如何将该字符串转换为数字,以便我可以将其转换为输出基础。
有什么想法吗?
How can I convert a number contained in a string from any base to any other base?
Bases can be anything i.e.: 2, 16, 10, 4, 8, 9.
I'm expecting the user to enter the base number. The user will enter the output base (the base to be converted to). The user will enter the number he wants to convert.
Pre thoughts:
I will save the input base and the output base in variables. Then I'll save the number he enters in a string (because he could enter any kind of number (hex, binary, base-5..).
I'm just trying to figure out how to convert that string to a number so i can convert it to the output base.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将数字 n 更改为基数 b 的一般算法类似于:(
请注意,answer[0] 保留答案的最低有效数字。)这有意义吗?您在执行此伪代码的哪一部分时遇到困难?
The general algorithm for changing a number n to base b goes something like:
(Note that answer[0] holds the least significant digit of the answer.) Does this make sense? Which part of this pseudocode are you having trouble implementing?
要将字符串转换为整数,您需要查看 ASCII 表。
迭代字符串中的每个字符,直到到达末尾,并基于字符是什么及其所在范围:“0”到“9”、“a”到“f”、“A”到“F” ,您需要减去其范围内底部字符的值并添加任何适当的数量。然后将其添加到累加器值中,您就可以开始了。我想您还需要检查是否有任何暗示该值的基数的值(例如,我希望十六进制值以“0x”为前缀)。
例如,如果您看到“1”,则需要减去“0”。如果您看到“a”,则需要减去“a”并添加 0x0a。
To convert from a string to an integer, you'll need to take a look at an ASCII table.
iterate through each character in your string until you hit the end, and based off of what the character is and which range it's in: '0' to '9', 'a' to 'f', 'A' to 'F', you'll need to subtract the value of the bottom character in it's range and add any appropriate amount. then add that to an accumulator value and you should be set to go. i guess you'll also need to check for any values that hint at what base the value is in (for instance, i'd expect hex values to be prefixed by "0x").
So for instance, if you see a '1', you'll need to subtract off '0'. if you see an 'a', you'll need to subtract off 'a' and add 0x0a.