Reputation: 13
I want to convert a string containing a binary number into an array of bytes. For that, I have this function:
private byte[] ToByteArray(string StringToConvert)
{
byte[] ByteArray = new byte[StringToConvert.Length/8];
byte temp;
for (int i = 0; i < StringToConvert.Length; i=i+8)
{
for (int j = i; j < 8; j++)
{
temp = Convert.ToByte(StringToConvert[j]);
ByteArray[i]=ByteArray[i] << temp;
}
}
return ByteArray;
}
I get an error that I can not convert byte to int(?) at
ByteArray[i]=ByteArray[i]<< temp;
What am I doing wrong?
Upvotes: 0
Views: 127
Reputation: 59655
This will convert a string containing a binary number like "001011101101011010101011"
into a byte array { 46, 214, 171 }
.
private Byte[] ToByteArray(String stringToConvert)
{
Contract.Requires(stringToConvert != null);
Contract.Requires(stringToConvert.Length % 8 == 0);
var result = new Byte[stringToConvert.Length / 8];
for (var index = 0; index < stringToConvert.Length / 8; index++)
{
result[index] = Convert.ToByte(stringToConvert.Substring(index * 8, 8), 2);
}
return result;
}
Upvotes: 1
Reputation: 9341
I'm going to read between the lines and guess that StringToConvert is a string containing multiples of 8 '0's or '1's, and that what you are trying to do is convert it to an array of bytes.
private byte[] ToByteArray(string StringToConvert)
{
byte[] ByteArray = new byte[StringToConvert.Length/8];
for (int i = 0; i < StringToConvert.Length/8; i++)
{
for (int j = 0; j < 8; j++)
{
char bitStr = StringToConvert[i*8+j];
ByteArray[i] = (byte)((ByteArray[i] << 1) | (bit=='1' ? 1 : 0));
}
}
return ByteArray;
}
Upvotes: 0
Reputation: 1796
Use
ByteArray[i] = (byte)(ByteArray[i] << temp);
As mentioned on MSDN (Shift Operators), the following is the predefined shift operators
int operator <<(int x, int count);
uint operator <<(uint x, int count);
long operator <<(long x, int count);
ulong operator <<(ulong x, int count);
and the byte values (ByteArray[i]
) matches the first operator specification which is then invoked and returns an int
value. So, to store the int
value in byte
, you have to typecast it to byte
. As int
to byte
is not implicit (data loss may occur), so you have to explicitly do the cast, as shown in the line above.
Upvotes: 0