Convert stringbinary to ascii - c#

i'm just started dev-ing app for wp7 and I'm trying to convert a string of binary back to ascii using c#.
But i have no idea how can it be done.
Hope someone could help me out here.
example :
Input string: 0110100001100101011011000110110001101111
Output string: hello

The simple solution,
using SubString and built in Convert.ToByte could look like this:
string input = "0110100001100101011011000110110001101111";
int charCount = input.Length / 8;
var bytes = from idx in Enumerable.Range(0, charCount)
let str = input.Substring(idx*8,8)
select Convert.ToByte(str,2);
string result = Encoding.ASCII.GetString(bytes.ToArray());
Console.WriteLine(result);
Another solution, doing the calculations yourself:
I added this in case you wanted to know how the calculations should be performed, rather than which method in the framework does it for you:
string input = "0110100001100101011011000110110001101111";
var chars = input.Select((ch,idx) => new { ch, idx});
var parts = from x in chars
group x by x.idx / 8 into g
select g.Select(x => x.ch).ToArray();
var bytes = parts.Select(BitCharsToByte).ToArray();
Console.WriteLine(Encoding.ASCII.GetString(bytes));
Where BitCharsToByte does the conversion from a char[] to the corresponding byte:
byte BitCharsToByte(char[] bits)
{
int result = 0;
int m = 1;
for(int i = bits.Length - 1 ; i >= 0 ; i--)
{
result += m * (bits[i] - '0');
m*=2;
}
return (byte)result;
}
Both the above solutions does basically the same thing: First group the characters in groups of 8; then take that sub string, get the bits represented and calculate the byte value. Then use the ASCII Encoding to convert those bytes to a string.

You can use the BitArray Class and use its CopyTo function to copy ur bit string to byte array
Then you can convert your byte array to string using Text.Encoding.UTF8.GetString(Byte[])
See this link on BitArray on MSDN

Related

How to convert Word or Number to list of Letters or Numbers?

I'm new for C#, but have some basic question:
I need to convert some words, for example: "Hello"(string) to list of letters" "H","e","l","l","o".
Or Number 3242, to list or array of numbers: [3,2,4,2].
How to do that?
And how after that I can change any number or letter in lists?
In Python its very easy. But in C# I don't know what to do.
Please provide LOGICAL and EASY solution. I don't need some 50 lines script which using 20 functions. I'm interested in basic understanding of that process with easy solution, if it existing.
Thank you guys,
P.S: i'm using .Net 3.1
You can use ToCharArray() function to convert input string to character array.
If it is a type other than string then first convert it to String
Copies the characters in this instance to a Unicode character array.
var input = "Hello world";
if(input is string) //Convert word to an array of char
return input.ToCharArray();
if(input is int) //Convert Number to an array of char
return input.ToString() //First convert number to string
.Select(x => int.Parse(x.ToString())) //Iterate over each digit and convert to int.
.ToArray(); //Convert IEnumerable to Array
As Prasad already told you what you have to use, Let me give you some examples about how you going to do it:
For String Type
Lets say there is a string:
string text = ".Net is Awesome";
To store this string as char[]:
char[] CharArray = text.ToCharArray();
To store this string as List<char>:
List<char> CharArray = text.ToCharArray().ToList();
Interestingly, for string Type variable you can directly use .ToList():
List<char> CharArray = text.ToList();
For Int Type
Now lets say you have an int:
int num = 123456;
To store this int as char[]:
char[] numArray = num.ToString().ToCharArray(); //Stored as char array no arithematic operation can be done.
Using Convert.ToInt32()
To store this int as int[]:
int[] numArray = num.ToString().Select(x => Convert.ToInt32(x)).ToArray(); //Arithematic Operations allowed
To store this int as List<int>:
List<int> numArray = num.ToString().Select(x => Convert.ToInt32(x)).ToList(); //Arithematic Operations allowed
Using int.Parse()
To store this int as int[]:
int[] numArray = num.ToString().Select(x => int.Parse(x.ToString())).ToArray(); //Arithematic Operations allowed
To store this int as List<int>:
List<int> numArray = num.ToString().Select(x => int.Parse(x.ToString())).ToList(); //Arithematic Operations allowed
Use below code
var inputStringData = "Hello";//string
var charArray = inputStringData.ToCharArray() ;
var inputNumberData = 3242;//Number
int[] result = inputNumberData.ToString().Select(o => Convert.ToInt32(o) - 48).ToArray();

String with index conversion or array of numbers

Why i can't convert this string to a number? Or how to make a array of numbers from this string.
string str = "110101010";
int c = Int32.Parse(str[0]);
str is a string so str[0] returns a char and the Parse method doesnt take a char as input but rather a string.
if you want to convert the string into an int then you would need to do:
int c = Int32.Parse(str); // or Int32.Parse(str[0].ToString()); for a single digit
or you're probably looking for a way to convert all the individual numbers into an array which can be done as:
var result = str.Select(x => int.Parse(x.ToString()))
.ToArray();
I assume you are trying to convert a binary string into its decimal representation.
For this you could make use of System.Convert:
int c = Convert.ToInt32(str, 2);
For the case that you want to sum up all the 1s and 0s from the string you could make use of System.Linq's Select() and Sum():
int c = str.Select(i => int.Parse(i.ToString())).Sum();
Alternatively if you just want to have an array of 1s and 0s from the string you could omit the Sum() and instead enumerate to an array using ToArray():
int[] c = str.Select(i => int.Parse(i.ToString())).ToArray();
Disclaimer: The two snippets above using int.Parse()would throw an exception if str were to contain a non-numeric character.
Int32.Parse accepts string argument, not char which str[0] returs.
To get the first number, try:
string str = "110101010";
int c = Int32.Parse(str.Substring(0, 1));

C# ByteString to ASCII String

I am looking for a smart way to convert a string of hex-byte-values into a string of 'real text' (ASCII Characters).
For example I have the word "Hello" written in Hexadecimal ASCII: 48 45 4C 4C 4F. And using some method I want to receive the ASCII text of it (in this case "Hello").
// I have this string (example: "Hello") and want to convert it to "Hello".
string strHexa = "48454C4C4F";
// I want to convert the strHexa to an ASCII string.
string strResult = ConvertToASCII(strHexa);
I am sure there is a framework method. If this is not the case of course I could implement my own method.
Thanks!
var str = Encoding.UTF8.GetString(SoapHexBinary.Parse("48454C4C4F").Value); //HELLO
PS: SoapHexBinary is in System.Runtime.Remoting.Metadata.W3cXsd2001 namespace
I am sure there is a framework method.
A a single framework method: No.
However the second part of this: converting a byte array containing ASCII encoded text into a .NET string (which is UTF-16 encoded Unicode) does exist: System.Text.ASCIIEncoding and specifically the method GetString:
string result = ASCIIEncoding.GetString(byteArray);
The First part is easy enough to do yourself: take two hex digits at a time, parse as hex and cast to a byte to store in the array. Seomthing like:
byte[] HexStringToByteArray(string input) {
Debug.Assert(input.Length % 2 == 0, "Must have two digits per byte");
var res = new byte[input.Length/2];
for (var i = 0; i < input.Length/2; i++) {
var h = input.Substring(i*2, 2);
res[i] = Convert.ToByte(h, 16);
}
return res;
}
Edit: Note: L.B.'s answer identifies a method in .NET that will do the first part more easily: this is a better approach that writing it yourself (while in a, perhaps, obscure namespace it is implemented in mscorlib rather than needing an additional reference).
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hexStr.Length; i += 2)
{
string hs = hexStr.Substring(i, 2);
sb.Append(Convert.ToByte(hs, 16));
}

How to split a string based on every third character regardless of what the character is in c# [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
.NET String.Format() to add commas in thousands place for a number
I am trying to add commas to a number for the presentation layer and need to cast and then split the number on every third character in order to join on a ','.
So if i have a string like this
546546555
desired output:
546,546,555
Other times, the number could be longer or shorter:
254654
desired output:
254,654
Is it possible to split in this manner then join with a comma?
tahnks!
EDIT:
Hi Everyone,
Thanks very much for your help.
To add to this post I also found a way to do this in SQL:
SUBSTRING(CONVERT(varchar, CAST(NumItems AS money), 1), 0, LEN(CONVERT(varchar, CAST(NumDocs AS money), 1)) - 2) as [NumDocs]
Rather than splitting the string manually, you should convert it to a number (or leave it as a number), and call the ToString method with the appropriate formatting:
Example
int value = 546546555;
string displayValue = value.ToString("#,#");
See this MSDN page for different format values:
C - Currency format
D - Decimal format
E - Scientific format
F - Fixed point format
G - General format
N - Number format
P - Percent format
R - Round trip format
X - Hexadecimal format
You should do this by converting your string to an integer, using Parse or ideally TryParse and use string formatting to display it:
var str = "546546555";
var formatted = String.Empty;
int value = 0;
if(int.TryParse(str,out value))
{
formatted = value.ToString("#,#");
}
Live example: http://rextester.com/FHO11833
Assuming you aren't only trying to output numbers, here's a quick function that I believe would do what you are after:
string splitter(string tosplit, int num, string splitstring)
{
string output = "";
for (int i = 0; i < tosplit.Length; i += num)
if (i + num < tosplit.Length)
output += tosplit.Substring(i, num) + ",";
else
output += tosplit.Substring(i);
return output;
}
Here, the output of splitter("546546555", 3, ",") would be 546,546,555
This would not be ideal for numbers though, as the other answers would cover this case perfectly.
Not very good code, but it works.
public static string GetString(string val, int number)
{
List<string> res = new List<string>();
res.Add("");
int counter = 0, i = 0;
while (i < val.Length)
{
while (res[counter].Length < number && i < val.Length)
{
res[counter] += val[i];
i++;
}
res.Add("");
counter++;
}
return string.Join(",", res.Where(r => !string.IsNullOrEmpty(r)));
}
val - your input string
number - number of characters you want to split, equals to 3 in your case
Gene S and Dan seem to have the answer IMHO. The nice thing about using the built in formatting is that you can write localizable code. For example, the "," is the numeric group separator in the US, but the "." is used in Spain.
var val = 12345678;
CultureInfo c = CultureInfo.CurrentCulture;
Application.CurrentCulture = new CultureInfo("EN-us");
var s = String.Format("{0:#,#}", val);
Application.CurrentCulture = new CultureInfo("ES-es");
var i = String.Format("{0:#,#}", val);
Application.CurrentCulture = c;

String operations in C#

Suppose I have a string "011100011".
Now I need to find another string by adding the adjacent digits of this string, like the output string should be "123210122".
How do I split each characters in the string and manipulate them?
The method that I thought was to convert the string to integer using Parsing and splitting each character using modulus or something and performing operations on them.
But can you suggest some simpler methods?
Here's a solution which uses some LINQ plus dahlbyk's idea:
string input = "011100011";
// add a 0 at the start and end to make the loop simpler
input = "0" + input + "0";
var integers = (from c in input.ToCharArray() select (int)(c-'0'));
string output = "";
for (int i = 0; i < input.Length-2; i++)
{
output += integers.Skip(i).Take(3).Sum();
}
// output is now "123210122"
Please note:
the code is not optimized. E.g. you might want to use a StringBuilder in the for loop.
What should happen if you have a '9' in the input string -> this might result in two digits in the output string.
Try converting the string to a character array and then subtract '0' from the char values to retrieve an integer value.
string input = "011100011";
int current;
for (int i = 0; i < input.Length; i ++)
{
current = int.Parse(input[i]);
// do something with current...
}

Categories

Resources