Sprache: C#
Einfache Methode die einen Bytewert in einen 8-Bit-String umwandelt.
private byte[] bitwert = { 128, 64, 32, 16, 8, 4, 2, 1 };
private byte[] bits = new byte[8];
public string dec2bin(byte Bytewert)
{
string bitstring = string.Empty; for (int Counter = 0; Counter < 8; Counter++)
{
if (Bytewert >= bitwert[Counter])
{
bits[Counter] = 1; Bytewert -= bitwert[Counter];
}
bitstring += Convert.ToString(bits[Counter]);
}
return bitstring;
}
private byte[] bitwert = { 128, 64, 32, 16, 8, 4, 2, 1 };
private byte[] bits = new byte[8];
public string dec2bin(byte Bytewert)
{
string bitstring = string.Empty; for (int Counter = 0; Counter < 8; Counter++)
{
if (Bytewert >= bitwert[Counter])
{
bits[Counter] = 1; Bytewert -= bitwert[Counter];
}
bitstring += Convert.ToString(bits[Counter]);
}
return bitstring;
}
Alte URL:
/snippet/dezimal-in-binaer-umwandeln/1264
Hi NB01,
ich hab das mal so gemacht:
public string dec2bin(long dezimalzahl, int bitanzahl)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bitanzahl; dezimalzahl = dezimalzahl >> 1,i++)
sb.Insert(0, dezimalzahl & 1);
return sb.ToString();
}
Damit ist man nicht auf ein Byte beschränkt und vermutlich läuft das bitshiften schneller als das -=.
Gruß,
Thomas
Hi zusammen,
warum eigentlich so kompliziert, das Framework hat doch genau diese Funktionalität schon?
[code]string bitstring = Convert.ToString(bytewert, 2).PadLeft(8,’0′);[/code]
Grüße
Martin