I'm trying to put the values of a string into a byte array with out changing the characters. This is because the string is in fact a byte representation of the data.
The goal is to move the input string into a byte array and then convert the byte array using:
string result = System.Text.Encoding.UTF8.GetString(data);
I hope someone can help me although I know it´s not a very good description.
EDIT:
And maybe I should explain that what I´m working on is a simple windows form with a textbox where users can copy the encoded data into it and then click preview to see the decoded data.
EDIT:
A little more code:
(inputText is a textbox)
private void button1_Click(object sender, EventArgs e)
{
string inputString = this.inputText.Text;
byte[] input = new byte[inputString.Length];
for (int i = 0; i < inputString.Length; i++)
{
input[i] = inputString[i];
}
string output = base64Decode(input);
this.inputText.Text = "";
this.inputText.Text = output;
}
This is a part of a windows form and it includes a rich text box. This code doesn´t work because it won´t let me convert type char to byte.
But if I change the line to :
private void button1_Click(object sender, EventArgs e)
{
string inputString = this.inputText.Text;
byte[] input = new byte[inputString.Length];
for (int i = 0; i < inputString.Length; i++)
{
input[i] = (byte)inputString[i];
}
string output = base64Decode(input);
this.inputText.Text = "";
this.inputText.Text = output;
}
It encodes the value and I don´t want that. I hope this explains a little bit better what I´m trying to do.
EDIT: The base64Decode function:
public string base64Decode(byte[] data)
{
try
{
string result = System.Text.Encoding.UTF8.GetString(data);
return result;
}
catch (Exception e)
{
throw new Exception("Error in base64Decode" + e.Message);
}
}
The string is not encoded using base64 just to be clear. This is just bad naming on my behalf.
Note this is just one line of input.
I've got it. The problem was I was always trying to decode the wrong format. I feel very stupid because when I posted the example input I saw this had to be hex and it was so from then on it was easy. I used this site for reference:
http://msdn.microsoft.com/en-us/library/bb311038.aspx
My code:
public string[] getHexValues(string s)
{
int j = 0;
string[] hex = new String[s.Length/2];
for (int i = 0; i < s.Length-2; i += 2)
{
string temp = s.Substring(i, 2);
this.inputText.Text = temp;
if (temp.Equals("0x")) ;
else
{
hex[j] = temp;
j++;
}
}
return hex;
}
public string convertFromHex(string[] hex)
{
string result = null;
for (int i = 0; i < hex.Length; i++)
{
int value = Convert.ToInt32(hex[i], 16);
result += Char.ConvertFromUtf32(value);
}
return result;
}
I feel quite dumb right now but thanks to everyone who helped, especially #Jon Skeet.
Are you saying you have something like this:
string s = "48656c6c6f2c20776f726c6421";
and you want these values as a byte array? Then:
public IEnumerable<byte> GetBytesFromByteString(string s) {
for (int index = 0; index < s.Length; index += 2) {
yield return Convert.ToByte(s.Substring(index, 2), 16);
}
}
Usage:
string s = "48656c6c6f2c20776f726c6421";
var bytes = GetBytesFromByteString(s).ToArray();
Note that the output of
Console.WriteLine(System.Text.ASCIIEncoding.ASCII.GetString(bytes));
is
Hello, world!
You obviously need to make the above method a lot safer.
Encoding has the reverse method:
byte[] data = System.Text.Encoding.UTF8.GetBytes(originalString);
string result = System.Text.Encoding.UTF8.GetString(data);
Debug.Assert(result == originalString);
But what you mean 'without converting' is unclear.
One way to do it would be to write:
string s = new string(bytes.Select(x => (char)c).ToArray());
That will give you a string that has one character for every single byte in the array.
Another way is to use an 8-bit character encoding. For example:
var MyEncoding = Encoding.GetEncoding("windows-1252");
string s = MyEncoding.GetString(bytes);
I'm think that Windows-1252 defines all 256 characters, although I'm not certain. If it doesn't, you're going to end up with converted characters. You should be able to find an 8-bit encoding that will do this without any conversion. But you're probably better off using the byte-to-character loop above.
If anyone still needs it this worked for me:
byte[] result = Convert.FromBase64String(str);
Have you tried:
string s = "....";
System.Text.UTF8Encoding.UTF8.GetBytes(s);
Related
I have a problem to display fo result of my looping code, this is my code
private int n = 689;
private int e = 41;
private int d = 137;
public void enkrip()
{
string text = "indra";
byte[] asciiBytes = Encoding.ASCII.GetBytes(text);
for (int i = 0; i < text.Length; i++)
{
int vout = Convert.ToInt32(asciiBytes[i]);
int c = (int)BigInteger.ModPow(vout, e, n);
char cipher = Convert.ToChar(c);
textBox2.Text = char.ToString(cipher);
}
}
but it not appear in textbox, any help?
You are overwriting the text in your box with each loop.
If you want the final string in your text box, your loop should build a string, and then once the loop is done, put the final string into your text box.
On each iteration of the loop you're setting the Text to a single character. Build the string up, and assign it to the text outside the loop
string text = "indra";
byte[] asciiBytes = Encoding.ASCII.GetBytes(text);
char[] result = new char[text.Length];
for (int i = 0; i < text.Length; i++)
{
int vout = Convert.ToInt32(asciiBytes[i]);
int c = (int)BigInteger.ModPow(vout, e, n);
char cipher = Convert.ToChar(c);
result[i] = cipher;
}
textBox2.Text = new string(result);
You're only ever going to see the last value in the text box, since you over-write the text box's .Text property in every iteration of the loop. Even if the UI does update between loop iterations, it would be too fast to perceive.
You could append to the text box in each iteration:
textBox2.Text += char.ToString(cipher);
Or perhaps build a string in the loop and then set the text box afterward (generally the preferred solution):
var sb = new StringBuilder();
for (int i = 0; i < text.Length; i++)
{
//...
sb.Append(char.ToString(cipher));
}
textBox2.Text = sb.ToString();
Probably, you want a combine all the results into a single string:
public void enkrip() {
string text = "indra";
byte[] asciiBytes = Encoding.ASCII.GetBytes(text);
// "iùŢĕ"
textBox2.Text = String.Concat(asciiBytes
.Select(b => (char)BigInteger.ModPow(b, e, n)));
}
please note, that asciiBytes.Length and text.Length are different values (in general case). To represent encrypted text as hex codes:
public void enkrip() {
string text = "indra";
byte[] asciiBytes = Encoding.ASCII.GetBytes(text);
// 0069, 00f9, 0162, 0115, 001c
textBox2.Text = String.Join(", ", asciiBytes
.Select(b => BigInteger.ModPow(b, e, n).ToString("x4")));
}
My final suggestion is to extract a method:
public static String Encrypt(String text) {
if (String.IsNullOrEmpty(text))
return text;
int n = 689;
int e = 41;
return String.Concat(Encoding.ASCII.GetBytes(text)
.Select(b => (char)BigInteger.ModPow(b, e, n)));
}
...
// and so you can encrypt as easy as
textBox2.Text = Encrypt("indra");
I want to convert/find each of my string characters to (int) and reverse this operation.
I manage to do the first part,but the seconds one is giving me some problems.
string input;
string encrypt = ""; string decrypt = "";
input = textBox.Text;
foreach (char c in input)
{
int x = (int)c;
string s = x.ToString();
encrypt += s;
}
MessageBox.Show(encrypt);
foreach (int i in encrypt)
{
char c = (char)i;
string s = c.ToString();
decrypt += c;
}
MessageBox.Show(decrypt);
Thanks!
Here is a fixed program according to my advise above
string encrypt = ""; string decrypt = "";
string input = Console.ReadLine();
var length = input.Length;
int[] converted = new int[length];
for (int index = 0; index < length; index++)
{
int x = input[index];
string s = x.ToString();
encrypt += s;
converted[index] = x;
}
Console.WriteLine(encrypt);
for (int index = 0; index < converted.Length; index++)
{
char c = (char)converted[index];
string s = c.ToString();
decrypt += s;
}
Console.WriteLine(decrypt);
This will not work as is, because you're adding numbers to a string with no padding.
Let's assume the first three letter's values are '1','2','3', you'll have a string with "123".
Now, if you know each letter is 1 int length, you're good, but what happens if 12 is valid? and 23?
This might not be a "real" issues in your case because the values will probably be all 2 ints long, but it's very lacking (unless it's homework, in which case, oh well ...)
The ascii values for the alphabet will go from 65 for A to 122 z.
You can either pad them (say 3 chars per number, so 065 for A, and so on), delimit them (have ".", and split the string on that), use an array (like shahar's suggestion), lists, etc etc ...
In Your scenario, encryption may give output as you expected but its hard to decrypt the encrypted text using such mechanism. so I just do some customization on your code and make it workable here.
i suggest a similar one here:
string input;
string encrypt = ""; string decrypt = "";
int charCount = 0;
input = "textBox.Text";
foreach (char c in input)
{
int x = (int)c;
string s = x.ToString("000");
encrypt += s;
charCount++;
}
// MessageBox.Show(encrypt);
while (encrypt.Length > 0)
{
int item = Int32.Parse(encrypt.Substring(0, 3));
encrypt = encrypt.Substring(3);
char c = (char)item;
string s = c.ToString();
decrypt += c;
}
Reason for your code is not working:
You have declared encrypt as string and iterate through each integer in that string value, it is quiet not possible.
if you make that loop to iterate through each characters in that string value again it gives confusion. as :
lets take S as your input. its equivalent int value is 114 so if you make a looping means it will give 1,1,4, you will not get s back from it.
I've been researching this everywhere and all the LRC implementation seems to not giving me the right answer. After spending few days on it, I decided to put my code here to see if anyone else can spot the problem.
Here's the code (C#)
//Input Data = "31303030315E315E31303030325E315E31303030375E39395E31303032325E36353631335E"
//LRC Answer = "30"
private static string LRC(string Data)
{
int checksum = 0;
foreach (char c in GetStringFromHex(Data))
{
checksum ^= Convert.ToByte(c);
}
string hex = checksum.ToString("X2");
Console.WriteLine("Calculated LRC = " + hex);
return hex;
}
//Supporting Function used in LRC function
private static string GetStringFromHex(string s)
{
string result = "";
string s2 = s.Replace(" ", "");
for (int i = 0; i < s2.Length; i += 2)
{
result += Convert.ToChar(int.Parse(s2.Substring(i, 2), System.Globalization.NumberStyles.HexNumber));
}
return result;
}
The current output shows "Calculated LRC = 33". However, the right answer is "30". Can anyone spot what's wrong with this?
Any help will be fantastic!
After several testing, it is confirmed LRC should include ETX and exclude STX during the LRC calculation.
I am a beginner learning c#.
I have coded a method that turns a two digit integer in a sequence of 16 bits
// takes input from user and convert it
private void Button_Click(object sender, RoutedEventArgs e)
{
string input = key.Text;
string mykey = "";
foreach (var item in input)
{
mykey += Binary(item);
}
key.Text = mykey;
}
private string Binary(Char ch)
{
string result = string.Empty;
int asciiCode;
char[] bits = new char[8];
asciiCode = (int)ch;
result = Convert.ToString(asciiCode, 2);;
bits = result.PadLeft(8, '0').ToCharArray();
return string.Join("",bits);
}
It might be a bit complicated but it is working. However my main problem is that I want to invert the process: ie from a sequence such as 0011000100110010 I should retrieve the int which is 12. Can someone help me to get on the right track?
Any help is greatly appriciated
Given the fact that you are learning C#, I will give you a simple, straightforward example even if it is not optimal or fancy. I think it would serve you purpose better.
static int GetInt(string value)
{
double result = 0d;//double
IEnumerable<char> target = value.Reverse();
int index = 0;
foreach (int c in target)
{
if (c != '0')
result += (c - '0') * Math.Pow(2, index);
index++;
}
return (int)result;
}
This code will work with any padding. Also, you can change it to Int16 if you will or extend it as you want. Also, it assumes that the given string has the least significant bit at the end (little endian).
var int16 = Convert.ToInt16("0011000100110010", 2);
Basically, I'm building a small tracker for experimental purposes. I've gotten quite far, and am now working on the announce part.
What I really can't figure out is how I should decode the info_hash query string provided.
From the specification, it is a urlencoded 20-byte SHA1 hash, which made me write this code,
byte[] foo = Encoding.Default.GetBytes(HttpUtility.UrlDecode(infoHash));
string temp = "";
foreach (byte b in foo)
{
temp += b.ToString("X");
}
Which gives 'temp' the following value,
5D3F3F3F3F5E3F3F3F153FE4033683F55693468
The first and last few characters are correct. This is the raw info_hash,
%5d%96%b6%f6%84%5e%ea%da%c5%15%c4%0e%403h%b9Ui4h
And this is what both uTorrent and my own tracker gives me as info_hash when generating it from the torrent file,
5D96B6F6845EEADAC515C40E403368B955693468
What am I doing wrong?
UrlDecode returns a string, but a SHA1 hash doesn't make sense if interpreted as (ANSI) string.
You need to decode the input string directly to an byte array, without the roundtrip to a string.
var s = "%5d%96%b6%f6%84%5e%ea%da%c5%15%c4%0e%403h%b9Ui4h";
var ms = new MemoryStream();
for (var i = 0; i < s.Length; i++)
{
if (s[i] == '%')
{
ms.WriteByte(
byte.Parse(s.Substring(i + 1, 2), NumberStyles.AllowHexSpecifier));
i += 2;
}
else if (s[i] < 128)
{
ms.WriteByte((byte)s[i]);
}
}
byte[] infoHash = ms.ToArray();
string temp = BitConverter.ToString(infoHash);
// "5D-96-B6-F6-84-5E-EA-DA-C5-15-C4-0E-40-33-68-B9-55-69-34-68"
HttpUtility.UrlDecodeToBytes