如何将整数转换为其二进制表示形式?在C中将整数转换为二进制文件#
我使用这个代码:
String input = "8";
String output = Convert.ToInt32(input, 2).ToString();
但它抛出一个异常:
找不到任何解析的数字
如何将整数转换为其二进制表示形式?在C中将整数转换为二进制文件#
我使用这个代码:
String input = "8";
String output = Convert.ToInt32(input, 2).ToString();
但它抛出一个异常:
找不到任何解析的数字
你的例子有一个整数表达为一个字符串。假设您的整数实际上是一个整数,并且您希望取整数并将其转换为二进制字符串。
int value = 8;
string binary = Convert.ToString(value, 2);
它返回1000
是否有任何类似的方法将二进制转换为十进制? – kashif 2013-01-24 08:26:14
@ kashif'int value = Convert.ToInt32(“1101”,2)'会给'value'的值13. – flindeberg 2013-03-05 18:20:15
Convert.ToInt32(string, base)
没有做基本转换到您的基础。它假定字符串包含在标明的基有效数字,并转换为基10
所以你得到一个错误,因为“8”是不是在基地的有效位数2.
String str = "1111";
String Ans = Convert.ToInt32(str, 2).ToString();
将显示15
(1111基座2 = 15个碱基10)
String str = "f000";
String Ans = Convert.ToInt32(str, 16).ToString();
将显示61440
。
using System;
class Program{
static void Main(string[] args){
try{
int i = (int)Convert.ToInt64(args[0]);
Console.WriteLine("\n{0} converted to Binary is {1}\n",i,ToBinary(i));
}catch(Exception e){
Console.WriteLine("\n{0}\n",e.Message);
}
}
public static string ToBinary(Int64 Decimal)
{
// Declare a few variables we're going to need
Int64 BinaryHolder;
char[] BinaryArray;
string BinaryResult = "";
while (Decimal > 0)
{
BinaryHolder = Decimal % 2;
BinaryResult += BinaryHolder;
Decimal = Decimal/2;
}
BinaryArray = BinaryResult.ToCharArray();
Array.Reverse(BinaryArray);
BinaryResult = new string(BinaryArray);
return BinaryResult;
}
你在这里重新发明轮子。 BCL已经包含了执行此操作的方法。 – Eltariel 2010-06-02 06:37:11
http://zamirsblog.blogspot.com/2011/10/convert-decimal-to-binary-in-c.html
public string DecimalToBinary(string data)
{
string result = string.Empty;
int rem = 0;
try
{
if (!IsNumeric(data))
error = "Invalid Value - This is not a numeric value";
else
{
int num = int.Parse(data);
while (num > 0)
{
rem = num % 2;
num = num/2;
result = rem.ToString() + result;
}
}
}
catch (Exception ex)
{
error = ex.Message;
}
return result;
}
不知道这与Xenon的答案有什么不同。 – 2012-11-08 17:22:26
他在氙气 – 2016-05-28 19:06:33
,没有额外的代码,只需输入,转换和输出非常简单。
using System;
namespace _01.Decimal_to_Binary
{
class DecimalToBinary
{
static void Main(string[] args)
{
Console.Write("Decimal: ");
int decimalNumber = int.Parse(Console.ReadLine());
int remainder;
string result = string.Empty;
while (decimalNumber > 0)
{
remainder = decimalNumber % 2;
decimalNumber /= 2;
result = remainder.ToString() + result;
}
Console.WriteLine("Binary: {0}",result);
}
}
}
+1之前回答了这个经典解决方案:) – 2014-09-27 14:11:44
对于通用字母表,这应该是{[...]} while(decimalNumber> 0); – 2015-03-04 15:51:11
**从任何经典基转换为任何碱在C#**
String number = "100";
int fromBase = 16;
int toBase = 10;
String result = Convert.ToString(Convert.ToInt32(number, fromBase), toBase);
// result == "256"
支持的碱是2,8,10和16
// I use this function
public static string ToBinary(long number)
{
string digit = Convert.ToString(number % 2);
if (number >= 2)
{
long remaining = number/2;
string remainingString = ToBinary(remaining);
return remainingString + digit;
}
return digit;
}
class Program{
static void Main(string[] args){
try{
int i = (int)Convert.ToInt64(args[0]);
Console.WriteLine("\n{0} converted to Binary is {1}\n",i,ToBinary(i));
}catch(Exception e){
Console.WriteLine("\n{0}\n",e.Message);
}
}//end Main
public static string ToBinary(Int64 Decimal)
{
// Declare a few variables we're going to need
Int64 BinaryHolder;
char[] BinaryArray;
string BinaryResult = "";
while (Decimal > 0)
{
BinaryHolder = Decimal % 2;
BinaryResult += BinaryHolder;
Decimal = Decimal/2;
}
// The algoritm gives us the binary number in reverse order (mirrored)
// We store it in an array so that we can reverse it back to normal
BinaryArray = BinaryResult.ToCharArray();
Array.Reverse(BinaryArray);
BinaryResult = new string(BinaryArray);
return BinaryResult;
}
}//end class Program
我知道这个答案看起来类似于大多数已经在这里的答案,但我注意到几乎没有人使用fo R-循环。这个代码可以工作,并且可以被认为是简单的,从某种意义上说,它可以在没有任何特殊功能的情况下工作,如带参数的ToString(),也不会太长。也许有些人喜欢for-loops而不是while-loop,这可能适合他们。
public static string ByteConvert (int num)
{
int[] p = new int[8];
string pa = "";
for (int ii = 0; ii<= 7;ii = ii +1)
{
p[7-ii] = num%2;
num = num/2;
}
for (int ii = 0;ii <= 7; ii = ii + 1)
{
pa += p[ii].ToString();
}
return pa;
}
原始的办法:
public string ToBinary(int n)
{
if (n < 2) return n.ToString();
var divisor = n/2;
var remainder = n % 2;
return ToBinary(divisor) + remainder;
}
class Program
{
static void Main(string[] args)
{
var @decimal = 42;
var binaryVal = ToBinary(@decimal, 2);
var binary = "101010";
var decimalVal = ToDecimal(binary, 2);
Console.WriteLine("Binary value of decimal {0} is '{1}'", @decimal, binaryVal);
Console.WriteLine("Decimal value of binary '{0}' is {1}", binary, decimalVal);
Console.WriteLine();
@decimal = 6;
binaryVal = ToBinary(@decimal, 3);
binary = "20";
decimalVal = ToDecimal(binary, 3);
Console.WriteLine("Base3 value of decimal {0} is '{1}'", @decimal, binaryVal);
Console.WriteLine("Decimal value of base3 '{0}' is {1}", binary, decimalVal);
Console.WriteLine();
@decimal = 47;
binaryVal = ToBinary(@decimal, 4);
binary = "233";
decimalVal = ToDecimal(binary, 4);
Console.WriteLine("Base4 value of decimal {0} is '{1}'", @decimal, binaryVal);
Console.WriteLine("Decimal value of base4 '{0}' is {1}", binary, decimalVal);
Console.WriteLine();
@decimal = 99;
binaryVal = ToBinary(@decimal, 5);
binary = "344";
decimalVal = ToDecimal(binary, 5);
Console.WriteLine("Base5 value of decimal {0} is '{1}'", @decimal, binaryVal);
Console.WriteLine("Decimal value of base5 '{0}' is {1}", binary, decimalVal);
Console.WriteLine();
Console.WriteLine("And so forth.. excluding after base 10 (decimal) though :)");
Console.WriteLine();
@decimal = 16;
binaryVal = ToBinary(@decimal, 11);
binary = "b";
decimalVal = ToDecimal(binary, 11);
Console.WriteLine("Hexidecimal value of decimal {0} is '{1}'", @decimal, binaryVal);
Console.WriteLine("Decimal value of Hexidecimal '{0}' is {1}", binary, decimalVal);
Console.WriteLine();
Console.WriteLine("Uh oh.. this aint right :(... but let's cheat :P");
Console.WriteLine();
@decimal = 11;
binaryVal = Convert.ToString(@decimal, 16);
binary = "b";
decimalVal = Convert.ToInt32(binary, 16);
Console.WriteLine("Hexidecimal value of decimal {0} is '{1}'", @decimal, binaryVal);
Console.WriteLine("Decimal value of Hexidecimal '{0}' is {1}", binary, decimalVal);
Console.ReadLine();
}
static string ToBinary(decimal number, int @base)
{
var round = 0;
var reverseBinary = string.Empty;
while (number > 0)
{
var remainder = number % @base;
reverseBinary += remainder;
round = (int)(number/@base);
number = round;
}
var binaryArray = reverseBinary.ToCharArray();
Array.Reverse(binaryArray);
var binary = new string(binaryArray);
return binary;
}
static double ToDecimal(string binary, int @base)
{
var val = 0d;
if (!binary.All(char.IsNumber))
return 0d;
for (int i = 0; i < binary.Length; i++)
{
var @char = Convert.ToDouble(binary[i].ToString());
var pow = (binary.Length - 1) - i;
val += Math.Pow(@base, pow) * @char;
}
return val;
}
}
学习资源:你需要了解你需要知道和多个二进制 https://www.mathsisfun.com/binary-number-system.html
一切
一切 - 包括算法将十进制转换为二进制 http://www.electronics-tutorials.ws/binary/bin_2.html
感谢您演示ToDecimal()方法。 – Rajiv 2017-06-17 08:13:29
static void Main(string[] args)
{
Console.WriteLine("Enter number for converting to binary numerical system!");
int num = Convert.ToInt32(Console.ReadLine());
int[] arr = new int[16];
//for positive integers
if (num > 0)
{
for (int i = 0; i < 16; i++)
{
if (num > 0)
{
if ((num % 2) == 0)
{
num = num/2;
arr[16 - (i + 1)] = 0;
}
else if ((num % 2) != 0)
{
num = num/2;
arr[16 - (i + 1)] = 1;
}
}
}
for (int y = 0; y < 16; y++)
{
Console.Write(arr[y]);
}
Console.ReadLine();
}
//for negative integers
else if (num < 0)
{
num = (num + 1) * -1;
for (int i = 0; i < 16; i++)
{
if (num > 0)
{
if ((num % 2) == 0)
{
num = num/2;
arr[16 - (i + 1)] = 0;
}
else if ((num % 2) != 0)
{
num = num/2;
arr[16 - (i + 1)] = 1;
}
}
}
for (int y = 0; y < 16; y++)
{
if (arr[y] != 0)
{
arr[y] = 0;
}
else
{
arr[y] = 1;
}
Console.Write(arr[y]);
}
Console.ReadLine();
}
}
我知道代码是非常基本的,不是很简单,但也可以使用负数 – 2017-03-23 15:37:46
您正在接收32位整数,但您的输出数组大小为16位。只是说... – 2017-11-19 21:36:52
是的,这句话是正确的。这段代码使用short是正确的,但它也适用于int。这个例子是小数字。如果我们想要使用大数字,则必须更改类型。我们的想法是,如果我们想要使用负数,结果至少应该大一个字节,这样程序才能看到这是一个反转的附加代码。 – 2017-11-21 12:48:42
BCL提供Convert.ToString(n, 2)
是好的,但如果你需要一个备用实现这几个基点高于BCL提供一个更快。
以下自定义实现适用于所有整数(-ve和+ ve)。从https://davidsekar.com/algorithms/csharp-program-to-convert-decimal-to-binary
static string ToBinary(int n)
{
int j = 0;
char[] output = new char[32];
if (n == 0)
output[j++] = '0';
else
{
int checkBit = 1 << 30;
bool skipInitialZeros = true;
// Check the sign bit separately, as 1<<31 will cause
// +ve integer overflow
if ((n & int.MinValue) == int.MinValue)
{
output[j++] = '1';
skipInitialZeros = false;
}
for (int i = 0; i < 31; i++, checkBit >>= 1)
{
if ((n & checkBit) == 0)
{
if (skipInitialZeros)
continue;
else
output[j++] = '0';
}
else
{
skipInitialZeros = false;
output[j++] = '1';
}
}
}
return new string(output, 0, j);
}
采取 原始来源上面的代码是我实现。所以,我很渴望听到任何反馈:)
int x=550;
string s=" ";
string y=" ";
while (x>0)
{
s += x%2;
x=x/2;
}
Console.WriteLine(Reverse(s));
}
public static string Reverse(string s)
{
char[] charArray = s.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
此功能将整数转换为二进制在C#:
public static string ToBinary(int N)
{
int d = N;
int q = -1;
int r = -1;
string binNumber = string.Empty;
while (q != 1)
{
r = d % 2;
q = d/2;
d = q;
binNumber = r.ToString() + binNumber;
}
binNumber = q.ToString() + binNumber;
return binNumber;
}
你们是不是要一个数字的字符串表示转换,或者实际数?你想转换为十进制或int?你的例子并不真的符合你的问题。 – womp 2010-06-02 04:18:12
如果你正在寻找将十进制转换为字节,你可以使用下面的代码:https://gist.github.com/eranbetzalel/5384006#file-decimalbytesconvertor-cs – 2013-04-14 20:14:33