[英]converting Binary Numbers in to decimal numbers
我需要一個程序來將二進制數轉換為 Java 或 C++ 中的十進制數。
有沒有人可以幫助我。
爪哇:
String binary = "110010101011";
int decimal = Integer.parseInt(binary, 2);
C++:
#include <cstdlib>
const char* binary = "110010101011";
int decimal = strtol(binary, NULL, 2);
使用二進制擴展。 例如 1101 1001 是:
(1 x 2^7) + (1 x 2^6) + (1 x 2^4) + (1 x 2^3) + (1 x 2^0)
這等於:
217 十進制。
這是算法:
1.) 提示用戶輸入一個二進制數。
2.) 將數字存儲在數組中。 第一個元素,即 anArray[0] 應包含值 1,第二個元素應包含值 0 。 . .
3.) 實現一個 for 循環來進行計算。
在 C++ 中,有庫函數“strtol”、“strtoull”等,它們采用字符串和基數進行轉換。 如果您需要超過 32 / 64 位,那么您可以使用僅受可用內存限制的 GMP 庫。
是的,我知道怎么做。
用:
String input0 = "1010";
String input1 = "10";
int number0 = Integer.parseInt(input0, 2);
int number1 = Integer.parseInt(input1, 2);
int sum = number0 + number1;`
好的 C 函數itoa
算法上(在 c/c++ 中):
const char* binary = "110010101011";
int decimal = 0;
while ( *binary )
{
decimal*=2;
decimal+=*binary-'0';
binary++ ;
}
請注意,這不會處理無效字符(二進制數字以外的任何字符)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.