[.NET] string convert to binary string

这段代码示范如何将 string 转换成 binary string

public string ToBinary(string str) { string converted = string.Empty; byte[] byteArray = GetByteArray(str); //create a memory stream MemoryStream stream = new MemoryStream(); //create BinaryWriter based on our MemoryStream BinaryWriter writer = new BinaryWriter(stream); try { //write out in binary writer.Write(byteArray); } catch (Exception ex) { return ex.Message; } //now we get to start the conversion: Loop through each //byte in the byte array for (int i = 0; i < byteArray.Length; i++) { for (int j = 0; j < 8; j++) { converted += (byteArray[i] & 0x80) > 0 ? "1" : "0"; byteArray[i] <<= 1; } } return converted; }

你可能感兴趣的:(.NET)