system.byte[] error c# when converting from string to byte - c#

i want to convert string to Byte[] in C# and with the help of previous topics i use this code :
string s = "0a";
System.Text.ASCIIEncoding encode = new System.Text.ASCIIEncoding();
byte[] b = encode.GetBytes(s);
Console.WriteLine(b);
but when i run this code it only prints : " System.byte[]"

I think I may have finally deciphered your question. Are you trying to get the hex digits of your string into an array?
I'm assuming that you want to take 2-digit hex values from a string and convert each lot into bytes. If not, I'm as lost as everyone else. Please note that I have not included any error checking!
byte[] data = new byte[s.Length/2];
for(int i = 0; i < s.Length/2; ++i)
{
byte val = byte.Parse(s.Substring(i*2,2), System.Globalization.NumberStyles.HexNumber);
data[i] = val;
}
foreach(byte bv in data)
{
Console.WriteLine(bv.ToString("X"));
}

If you want do this Console.WriteLine(b) it will prints the type of b which is System.Byte[].
In order to print the string stored in byte[] b, just make use of System.Text.ASCIIEncoding.GetString(byte[] b);
so in your case, encode.GetString(b); will get your string.

You can use BitConverter class Check: http://msdn.microsoft.com/en-us/library/3a733s97(v=vs.100).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2
System.Text.ASCIIEncoding encode = new System.Text.ASCIIEncoding();
byte[] b = encode.GetBytes(s);
Console.WriteLine(BitConverter.ToString(b));

Your code already does the trick of converting string to byte, if your query is to print individual byte value, why not use a loop to print the value in byte array:
foreach (byte bb in b)
{
Console.Write(Convert.ToInt32(bb));
}

That's because it's returning the type of the object that you are typing. If you want to print the content of the array, try this:
Arrays.toString(byteArray)

Related

I need to convert a string data from byte to float

I have a text box and I need to convert the value I entered.
and in the end i guess i need to convert Double into a data.
but there is something wrong
example code:
textbox1.Text = "24.5";
double data = int.Parse(textbox1.Text);
byte[] b = BitConverter.GetBytes((data)f);
int i = BitConverter.ToInt32(b, 0);
code working like this
byte[] b = BitConverter.GetBytes(22.3f);
int i = BitConverter.ToInt32(b, 0);
how can i insert string data ?
int.Parse() is wrong and will likely throw an exception. If you have the string value "24.5", what do you expect an integer to do with the ".5" portion?
Try this:
textbox1.Text = "24.5";
double data = double.Parse(textbox1.Text);
Even better if you use one of the double.TryParse() overloads.
I don't think you can write
byte[] b = BitConverter.GetBytes((data)f);
(data)f -> is not valid. I think you wanted to use it like 24.5f. Try to cast it into float. For example:
byte[] b = BitConverter.GetBytes((float) data);
Furthermore why would you parse a string as an int into a double? Parse the string directly as double.
Look at #Joel Coehoorn comment.
For more information about Double.TryParse() look at: Microsofts handbook about Double.TryParse

C# char into int bigger than 256

i need to convert some char to int value but bigger than 256. This is my function to convert int to char. I need reverse it
public static string chr(int number)
{
return ((char)number).ToString();
}
This function doesnt work - its returning only 0-256, ord(chr(i))==i
public static int ord(string str)
{
return Encoding.Unicode.GetBytes(str)[0];
}
The problem is that your ord function truncates the character of the string to the first byte, as interpreted by UNICODE encoding. This expression
Encoding.Unicode.GetBytes(str)[0]
// ^^^
returns the initial element of a byte array, so it is bound to stay within the 0..255 range.
You can fix your ord method as follows:
public static int Ord(string str) {
var bytes = Encoding.Unicode.GetBytes(str);
return BitConverter.ToChar(bytes, 0);
}
Demo
Since you don't care much about encodings and you directly cast an int to a char in your chr() function, then why dont you simply try the other way around?
Console.WriteLine((int)'\x1033');
Console.WriteLine((char)(int)("\x1033"[0]) == '\x1033');
Console.WriteLine(((char)0x1033) == '\x1033');
char is 2 bytes long (UTF-16 encoding) in C#
char c1; // TODO initialize me
int i = System.Convert.ToInt32(c1); // could be greater than 255
char c2 = System.Convert.ToChar(i); // c2 == c1
System.Convert on MSDN : https://msdn.microsoft.com/en-us/library/system.convert(v=vs.110).aspx
Characters and bytes are not the same thing in C#. The conversion between char and int is a simple one: (char)intValue or (int)myString[x].

Convert a string into BASE62

I'm looking for the c# code to convert a string into BASE62, like this:
http://www.molengo.com/base62/title/base62-encoder-decoder
I need those encode and decode-methods for URL-Encoding.
Background on BINARY to TEXT Encoding schemes:
https://en.wikipedia.org/wiki/Base62
https://en.wikipedia.org/wiki/Base64
Good explanation of the BASE62 encoding scheme:
https://www.codeproject.com/Articles/1076295/Base-Encode
Try the C# libraries available here which adds some extension methods to allow you to convert a byte array to and from BASE62 (binary-to-text encoding schemes).
Plenty of base62 libraries on github, have a look:
https://github.com/JoyMoe/Base62.Net
https://github.com/ghost1face/base62
https://github.com/rossdempster/base62csharp
https://github.com/renmengye/base62-csharp (claims below that it doesn't work...raise any issues with them)
If your source data is contained in a "string" then you would first need to convert your "string" to a suitable byte array.
But be careful, to use the correct string to byte conversion call....as you may want the bytes to be the ASCII characters, or the Unicode byte stream etc i.e. Encoding.GetBytes(text) or System.Text.ASCIIEncoding.ASCII.GetBytes(text);, etc
byte[] bytestoencode = .....
string encodedasBASE62 = bytestoencode.ToBase62();
.....
byte[] bytesdecoded = encodedasBASE62.FromBase62();
You can do this for any base, this way:
static string ToBase62(ulong number)
{
var alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var n = number;
ulong basis = 62;
var ret = "";
while (n > 0)
{
ulong temp = n % basis;
ret = alphabet[(int)temp] + ret;
n = (n / basis);
}
return ret;
}
not the real answer but hopefully this helps you to build a C# Version of it:
Javascript Base62 Encode/Decode:
http://x443.wordpress.com/2012/03/18/javascript-base62-encode-decode/

Binary data conversion to string

I have a chunk of binary data which contains structures with offsets and then strings;
in C++ it is easy:
struct foo
{
int offset;
char * s;
}
void * data;
... data is read and set
foo * header = (foo*) data;
header->s = (int)header-> + (int)data;
int len = strlen(header->s);
char* ns = new char[len+1];
strcpy(ns,header->s);
simple enough...
in C# how would you do this?
The biggest problem is that I don't know the length of the string. It is null terminated.
I have the data in a byte[] and an IntPtr to the memory but I need a POINTER to that data a a string (char *) something that I can get the length of the string.
C# is a high level language, and working with pointers is simply unnatural for this language.
To convert the data from byte array to a string, you can use the BitConverter class:
BitConverter.ToInt32(byte_array, start index);
To convert it to a string, you can use the StringBuilder class:
StringBuilder str = new StringBuilder();
// i=starting index of text
for (int i = 3; i<byte_array.Length; i++)
str.Append(byte_array[i];
return str.ToString();
If there is more data after the string, you can put the stopping condition for the loop byte_array[i]!=0, and when it stops, byte_array[i] will be the string terminator. Save the value of i, and you can get the data after it.
Another method of doing this is to use the ASCIIEncoding.ASCII.GetString() method:
ASCIIEncoding.ASCII.GetString(byte_array, start_index, bytes_count);

How to display text being held in a int variable?

My variable holds some text but is currently being stored as an int (the class used reads the bytes at a memory address and converts to int. Variable.ToString just displays the decimal representation, but doesn't encode it to readable text, or in other words, I would now like to convert the data from int to string with ascii encoding or something.
Here is a demo (based on our Q+A above).
Note: Settings a string with the null terminator as a test, then encoding it into ASCII bytes, then using unsafe (you will need to allow that in Build Option in project properties), itearte through each byte and convert it until 0x0 is reached.
private void button1_Click(object sender, EventArgs e)
{
var ok = "OK" + (char)0;
var ascii = Encoding.ASCII;
var bin = ascii.GetBytes( ok );
var sb = new StringBuilder();
unsafe
{
fixed (byte* p = bin)
{
byte b = 1;
var i = 0;
while (b != 0)
{
b = p[i];
if (b != 0) sb.Append( ascii.GetString( new[] {b} ) );
i++;
}
}
}
Console.WriteLine(sb);
}
Note the FIXED statement, this is required managed strings/arrayts etc are not guaranteed to be statically placed in memory - this ensures it during that section.
assuming an int variable
int x=10;
you can convert this into string as
string strX = x.ToString();
Try this
string s = "9quali52ty3";
byte[] ASCIIValues = Encoding.ASCII.GetBytes(s);
foreach(byte b in ASCIIValues) {
Console.WriteLine(b);
}
Int32.ToString() has an overload that takes a format string. Take a look at the available format strings and use one of those.
Judging by your previous question, the int you have is (probably) a pointer to the string. Depending on whether the data at the pointer is chars or bytes, do one of these to get your string:
var s = new string((char*)myInt);
var s = new string((sbyte*)myInt);
OK. If you variable is a pointer, then Tim is pointing you in the right direction (assuming it is an address and not an offset from an address - in which case you will need the start address to offset from).
If, on the other hand, your variable contains four encoded ascii characters (of a byte each), then you need to split to bytes and convert each byte to a character. Something like this Console.WriteLine(TypeDescriptor.GetConverter(myUint).ConvertTo(myUint, typeof(string))); from Here - MSDN ByteConverter

Categories