简体   繁体   English

从char *到二进制的十进制

[英]Decimal from a char* to binary

I have a string that consists some decimal value, with number of digits can be more than any existing int-types can hold(I know the number of digits). 我有一个包含一些十进制值的字符串,其位数可以比任何现有的int类型都要多(我知道数字的位数)。 Give me some hints, please, how can I convert that number to it's binary representation (so I will have other char* variable, that will consist binary). 请给我一些提示,请问如何将该数字转换为二进制表示(因此我将使用其他char *变量,它将包含二进制)。

您可以使用类似GNU Multiple Precision库的东西,它支持很长的数字。

You'll need a custom BigInt library. 您需要一个自定义BigInt库。 GMP would be a good choice. GMP将是一个不错的选择。

Just some hints (if you want to implement it by hand). 只是一些提示(如果你想手动实现)。

I did that (homework) this way: 我这样做(作业):

  1. I used an array of unsigned int to store the bit representing the number(using two's complement representation). 我使用unsigned int数组来存储表示数字的位(使用二进制补码表示)。
  2. I implemented shift and addition operations on that array (with the same semantic of classical integrals type). 我在该数组上实现了移位和加法运算(具有与经典积分类型相同的语义)。
  3. Since you can express a number with sum of products I used an algorithm with shift and add(like shown on this post ). 既然你可以表达对产品和一些我使用的算法与移位和加法(如显示在这个职位 )。 You can use the position of a single character in the string to generate the right binary representation. 您可以使用字符串中单个字符的位置来生成正确的二进制表示。

(I don't know if there are better or faster solutions.) I won't post the code, this way you can enjoy to do it yourself ;) (我不知道是否有更好或更快的解决方案。)我不会发布代码,这样你就可以享受自己做的;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM