I want to create a data packet and write it to socket.
This packet starts with 'C0' hex value.
In php I easily can create it with this code:
$a = "\xC0";
now I want to create it in c#. How can do this?
In C#, strings are Unicode-encoded, so you shouldn't use them for binary data. Instead use a byte array.
To create a byte array starting with C0, do something like this:
byte[] packet = new byte[] { 0xC0, /* Other values */ };
If you have an existing string that you want to send, you can use Encoding.ASCII to convert it to the bytes you need.
If you are sending bytes it's as easy as:
byte a = 0xC0;
If the packet contains text, you can start a string:
string a = "\xC0";
For more information on String Literals: http://msdn.microsoft.com/en-us/library/aa691090(v=vs.71).aspx
Related
I want to convert unicode string to UTF8 string. I want to use this UTF8 string in SMS API to send unicode SMS.
I want conversion like this tool
https://cafewebmaster.com/online_tools/utf8_encode
eg. I have unicode string "हैलो फ़्रेंड्स" and it should be converted into "हà¥à¤²à¥ à¥à¥à¤°à¥à¤à¤¡à¥à¤¸"
I have tried this but not getting expected output
private string UnicodeToUTF8(string strFrom)
{
byte[] bytes = Encoding.Default.GetBytes(strFrom);
return Encoding.UTF8.GetString(bytes);
}
and calling function like this
string myUTF8String = UnicodeToUTF8("हैलो फ़्रेंड्स");
I don't think this is possible to answer concretely without knowing more about the SMS API you want to use. The string type in C# is UTF-16. If you want a different encoding, it's given to you as a byte[] (because a string is UTF-16, always).
You could 'cast' that into a string by doing something like this:
static string UnicodeToUTF8(string from) {
var bytes = Encoding.UTF8.GetBytes(from);
return new string(bytes.Select(b => (char)b).ToArray());
}
As far as I can tell this yields the same output as the website you linked. However, without knowing what API you're handing this string off to, I can't guarantee that this will ultimately work.
The point of string is that we don't need to worry about its underlying encoding, but this casting operation is kind of a giant hack and makes no guarantees that string represents a well-formed string anymore.
If something expects a UTF-8 encoding, it should accept a byte[], not a string.
Try this:
string output = "hello world";
byte[] bytes1 = Encoding.Convert(Encoding.Unicode, Encoding.UTF8, Encoding.Unicode.GetBytes(output));
byte[] bytes2 = Encoding.Convert(Encoding.Unicode, Encoding.Unicode, Encoding.Unicode.GetBytes(output));
var output1 = Encoding.UTF8.GetString(bytes1);
var output2 = Encoding.Unicode.GetString(bytes2);
You will see that bytes1 is 11 bytes (1 byte per char UTF-8) and bytes2 is 22 bytes (2 bytes per char for unicode)
I'm trying to encode some strings back and forth from base-64 string and I'm having truble to get the right result.
string text = base64string.... //Here I have a base-64 string.
byte[] encodedByte = System.Text.ASCIIEncoding.ASCII.GetBytes(text);
string base64Encoded = Convert.ToBase64String(encodedByte);
if (text == base64Encoded) //If the new encoded string is equal to its original value
return base64Encoded;
I have tried my ways to do this and I don't seem to get the right result. I have tried both with System.Text.Encoding.Unicode and System.Text.Encoding.UTF8
What could be the problem? Does anyone have a proper solution?
string text = base64string.... //Here I have a base-64 string.
byte[] encodedByte = System.Text.ASCIIEncoding.ASCII.GetBytes(text);
string base64Encoded = Convert.ToBase64String(encodedByte);
You are double encoding the string. You begin with a base64 string, get the bytes, and then encode it again. If you want to compare you will need to begin with the original string.
If text is a base-64 string, then you are doing it backwards:
byte[] raw = Convert.FromBase64String(text); // unpack the base-64 to a blob
string s = Encoding.UTF8.GetString(raw); // assume the blob is UTF-8, and
// decode to a string
which will get you it as a string. Note, though, that this scenario is only useful for representing unicode text in an ascii format. Normally you wouldn't base-64 encode it if the original contents are string.
Convert whatever it is that you need in Base64 into a Byte array then use the FromBase64String and ToBase64String to convert to and from Base64:
Byte[] buffer = Convert.FromBase64String(myBase64String1);
myBase64String2 = Convert.ToBase64String(buffer);
myBase64String1 will be equal to myBase64String2. You will need to use other methods to get your data type into a Byte array and the reverse to get your data type back. I have used this to convert the content of a class into a byte array and then to Base64 string and write the string to the filesystem. Later I read it back into a class instance by reversing the process.
You have the encoding code correctly laid out. To confirm whether the base64-encoded string is correct, you can try decoding it and comparing the decoded contents to the original:
var decodedBytes = Convert.FromBase64String(base64encoded);
var compareText = System.Text.Encoding.ASCII.GetString(decodedText);
if (text == compareText)
{
// carry on...
return base64encoded;
}
hello i use a form of message parsing in which i write fields into a buffered stream, and then extract a byte array repesantaition of that stream
MyMessage _message = new MyMessage("me","you",MessageType.peer_message,4252422) ;
// in the constructor String sender,String receiver,MessageType(enumaraition) m_type,Int32 id
byte [] buffer = myEncoder.encode(message) ;
now when i pass this to myDecoder it decodes it in the same metter and it works great !
how i do that is not the issue
my issue is that in some cases of misscommunicaition i need to store the byte[] array (buffer) for farther use , and i'm trying to do that in an xmlDocumant under a tag
HERE IN THE INNER TEXT IS WHERE I WOULD LIKE TO SAVE THAT ARRAY OF BYTES
ive tryed -->
utf8Encoding.Ascii.getString(buffer) which save some kind of repsantaition
but it changes values of field wich are not strings... when i take it out by using
utf8Encoding.Ascii.getBytes(packet_node.innerText) ;
1)THE QUESTION IS HOW WOULD U GO ABOUT SAVING THAT BYTE ARRAY TO A XMLNODE
2)i've also tried just writing the fields one by one in each tag
<Packet>
<sender>me</sender>
<receiver>him</receiver>
<MessageType> ..?? how would i represent a byte as a string ? </MessageType>
<Id> 4252353523 </Id> here i have no problem but i still would have to always prase the value back and forth in other uses from int to string ..
</Packet>
3) so my conclusion is to serialize the byte array to an xmldocument .. just that i don't want it to be a document but just one node in an existing document
Encode it as a base-64 string. Just remember to decode it when you read it back.
byte[] bytes = ...;
string encoded = Convert.ToBase64String(bytes);
byte[] decoded = Convert.FromBase64String(encoded);
I have a UTF-8 byte array of data. I would like to search for a specific string in the array of bytes in C#.
byte[] dataArray = (some UTF-8 byte array of data);
string searchString = "Hello";
How do I find the first occurrence of the word "Hello" in the array dataArray and return an index location where the string begins (where the 'H' from 'Hello' would be located in dataArray)?
Before, I was erroneously using something like:
int helloIndex = Encoding.UTF8.GetString(dataArray).IndexOf("Hello");
Obviously, that code would not be guaranteed to work since I am returning the index of a String, not the index of the UTF-8 byte array. Are there any built-in C# methods or proven, efficient code I can reuse?
Thanks,
Matt
One of the nice features about UTF-8 is that if a sequence of bytes represents a character and that sequence of bytes appears anywhere in valid UTF-8 encoded data then it always represents that character.
Knowing this, you can convert the string you are searching for to a byte array and then use the Boyer-Moore string searching algorithm (or any other string searching algorithm you like) adapted slightly to work on byte arrays instead of strings.
There are a number of answers here that can help you:
byte[] array pattern search
Try the following snippet:
// Setup our little test.
string sourceText = "ʤhello";
byte[] searchBytes = Encoding.UTF8.GetBytes(sourceText);
// Convert the bytes into a string we can search in.
string searchText = Encoding.UTF8.GetString(searchBytes);
int position = searchText.IndexOf("hello");
// Get all text that is before the position we found.
string before = searchText.Substring(0, position);
// The length of the encoded bytes is the actual number of UTF8 bytes
// instead of the position.
int bytesBefore = Encoding.UTF8.GetBytes(before).Length;
// This outputs Position is 1 and before is 2.
Console.WriteLine("Position is {0} and before is {1}", position, bytesBefore);
In my application i write the code like this
byte[] byt = new byte[Convert.ToSbyte(textbox1.Text)];
it is giving the error that input string was not in a correct format.
This is a wild guess, but are you trying to convert the contents of the text box into a byte array? If so, you can do it like this:
byte[] byt = Encoding.UTF8.GetBytes(textbox1.Text);
The text in textbox1 is not a valid numeral for a signed byte.
Does it have spaces? Letters? ...?
What are you trying to do? The new byte[num] creates an array of 'num' bytes, where 'num' is usually an integer. All bytes in the array are then 0.
It doesn't create a filled array, as I suspect you may be trying to do.
What are the contents of that textbox1.Text that gave the error?
what you want in fact is this
// C# to convert a string to a byte array.
public static byte[] StrToByteArray(string str)
{
System.Text.ASCIIEncoding encoding=new System.Text.ASCIIEncoding();
return encoding.GetBytes(str);
}