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
Related
When I receive data from unmanaged code written in C (WinAPI) it asks to reserve a number of bytes and pass the handle (pointer) to the string.
Using Marshal.AllocHGlobal(150) didit.
In return, I received the number of chars, terminated by '/0' - C style.
When I build string from this char array using new string(charBuff) it doesn't cut the string at the '/0' point.
Well, I could use Substring + IndexOf, but is there any elegant way to cut it using some special existing method?
Ok, I found it after wakening up.
It's
Marshal.PtrToStringUni(IntPtr)
string MyStringFromWinAPI()
{
string result;
IntPtr strPtr = Marshal.AllocHGlobal(500);
// here would be any API that gets reserved buffer to rerturn string value
SendMessage(camHwnd, WM_CAP_DRIVER_GET_NAME_UNICODE, 500, strPtr);
// now you could follow 2 ways
// 1-st one is long and boring
char[] charBuff = new char[500];
Marshal.Copy(strPtr, charBuff, 0, 500);
Marshal.FreeHGlobal((IntPtr)strPtr);
result = new string(charBuff);
result = result.Substring(0, result.IndexOf('\0'));
return result;
// or more elegant way
result = Marshal.PtrToStringUni(strPtr);
Marshal.FreeHGlobal((IntPtr)strPtr);
return result;
}
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)
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/
How can i make bitwise operations on strings at c#
example
string sr1="0101110";
string sr2="1101110";
sr1 & sr2="0101110";
or
sr1 | sr2="1101110";
How can i make such comparison ?
Notice string lengths are fixed 1440 characters
Here my dirty solution
private string compareBitWiseAnd(string sr1, string sr2)
{
char[] crArray1 = sr1.ToCharArray();
char[] crArray2 = sr2.ToCharArray();
StringBuilder srResult = new StringBuilder();
for (int i = 0; i < crArray1.Length; i++)
{
if (crArray1[i] == crArray2[i])
{
srResult.Append(crArray1[i]);
}
else
{
srResult.Append('0');
}
}
return srResult.ToString();
}
private string compareBitWiseOr(string sr1, string sr2)
{
char[] crArray1 = sr1.ToCharArray();
char[] crArray2 = sr2.ToCharArray();
StringBuilder srResult = new StringBuilder();
for (int i = 0; i < crArray1.Length; i++)
{
if (crArray1[i] == '1' || crArray2[i] == '1')
{
srResult.Append("1");
}
else
{
srResult.Append('0');
}
}
return srResult.ToString();
}
Convert to actual bits first, and then do the bitwise comparison.
int num1 = Convert.ToInt32(sr1, 2);
int num2 = Convert.ToInt32(sr2, 2);
int result = num1 & num2;
Use this if you want to get a binary string from the result.
BigInteger is the type you are looking for. It also have BitwiseOr.
If you really need to stick with strings it is not very hard to compute bitwise operations on character-by-character basis... but I'd avoid doing it if possible.
And here is a question on how to construct BigInteger from string of any base - BigInteger Parse Octal String?
var bitString = "10101";
BigInteger value = bitString.Aggregate(new BigInteger(), (b, c) => b * 2 + c - '0');
You have to convert the string to numbers first, you can use "Convert.ToInt32(String, Int32)", the second parameter lets you specify the base:
string sr1 = "0101110";
string sr2 = "1101110";
int one = Convert.ToInt32(sr1, 2);
int two = Convert.ToInt32(sr2, 2);
int result = one & two;
hope it helps.
You can't do bitwise operations on a string in the way you intend. There are interesting things you can do with bitwise operations on strings with other goals, like changing their case, but I think this is what you want:
// Convert the string to an integer
int foo = Convert.ToInt32(sr1, 2);
int bar = Convert.ToInt32(sr2, 2);
// Perform binary styff
int result = foo & bar;
// Convert back to a string, if you want
string resultStr = result.ToString();
I like Alexei's BigInteger solution, but it does require .NET 4.0 minimum. If for some reason you can't use that, then another option is to use the BitArray class, which has been available since .NET 1.1. Unfortunately, there is no method built-in to BitArray to parse a binary string, so you have to do that manually, similar to Alexei's solution.
Another option is a class I wrote called BoolArray which does a lot of the same things as BitArray, but does have a method to parse binary strings - use the static BoolArray.FromBinaryString method:
BoolArray bin = BoolArray.FromBinaryString("1001011000111010101"); // etc
Here is the BoolArray source code. Note, however, that it isn't quite complete, and isn't fully tested either, but I'm not immediately aware of any bugs.
EDIT: I noticed after pasting the original link that the code used a function provided in a different class of my "Utils" library, and wouldn't have compiled directly. I've updated the link to provide this class in the code as well... hopefully that was the only case, but if not let me know and I can fix.
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);