I have this code:
string result = "";
foreach(char item in texte)
{
result += Convert.ToString(item, 2).PadLeft(8, '0');
}
So I have string named result which is conversion of a word like 'bonjour' in binary.
for texte = "bonjour" I have string result = 01100010011011110110111001101010011011110111010101110010 as type integer.
And when I do
Console.writeLine(result[0])
I obtain 0, normal, what I expected, but if I do
Console.WriteLine((int)result[0])
or
Console.WriteLine(Convert.ToInt32(result[0]))
I obtain 48!
I don't want 48, I want 0 or 1 at the type integer.
Could you help me please?
You can just subtract 48 from it!
Console.WriteLine(result[0] - 48);
because the characters digits 0-9 are encoded as 48 to 57.
If you want to access each bit by index, I suggest using a BitArray instead:
var bytes = Encoding.ASCII.GetBytes("someString");
var bitArray = new BitArray(bytes);
// now you can access the first bit like so:
bitArray.Get(0) // this returns a bool
bitArray.Get(0) ? 1 : 0 // this gives you a 1 or 0
string a = "23jlfdsa890123kl21";
byte[] data = System.Text.Encoding.Default.GetBytes(a);
StringBuilder result = new StringBuilder(data.Length * 8);
foreach (byte b in data)
{
result.Append(Convert.ToString(b, 2).PadLeft(8, '0'));
}
you can try this code.
Just Do this
Console.WriteLine(Convert.ToInt32(Convert.ToString(result[0])));
You're expecting it to behave the same as Convert.ToInt32(string input) but actually you're invoking Convert.ToInt32(char input) and if you check the docs, they explicitly state it will return the unicode value (in this case the same as the ASCII value).
http://msdn.microsoft.com/en-us/library/ww9t2871(v=vs.110).aspx
Related
I have json string as in example below
{"SaleToPOIRequest":{"MessageHeader":{"ProtocolVersion":"2.0","MessageClass":"Service","MessageCategory":"Login","MessageType":"Request","ServiceID":"498","SaleID":"SaleTermA","POIID":"POITerm1"},"LogoutRequest":{}}}
I want to convert json request to hexadecimal. I tried example in this link but i cannot get the exact conversion because of {,:,",} values.
Actually i can get hexadecimal return but when i reconvert to string i got return as below
{"SaleToPOIReque§7B#§²$ÖW76vTVder":{"ProtocolV¦W'6öâ#¢#"ã"Â$ÚessageClass":"Se§'f6R"Â$ÖW76vT:ategory":"Login"¢Â$ÖW76vUGR#¢*Request","Servic¤B#¢#C"Â%6ÆZID":"SaleTermA",¢%ôB#¢%ôFW&Ú1"},"LogoutReque§7B#§·×
that is not usefull for me
Is there any way to convert this?
So basically the problem is not only converting to hex but also converting back.
This is nothing more then combining 2 answers already on SO:
First for converting we use the answer given here: Convert string to hex-string in C#
Then for the converting back you can use this answer:
https://stackoverflow.com/a/724905/10608418
For you it would then look something like this:
class Program
{
static void Main(string[] args)
{
var input = "{\"SaleToPOIRequest\":{\"MessageHeader\":{\"ProtocolVersion\":\"2.0\",\"MessageClass\":\"Service\",\"MessageCategory\":\"Login\",\"MessageType\":\"Request\",\"ServiceID\":\"498\",\"SaleID\":\"SaleTermA\",\"POIID\":\"POITerm1\"},\"LogoutRequest\":{}}}";
var hex = string.Join("",
input.Select(c => String.Format("{0:X2}", Convert.ToInt32(c))));
var output = Encoding.ASCII.GetString(FromHex(hex));
Console.WriteLine($"input: {input}");
Console.WriteLine($"hex: {hex}");
Console.WriteLine($"output: {output}");
Console.ReadKey();
}
public static byte[] FromHex(string hex)
{
byte[] raw = new byte[hex.Length / 2];
for (int i = 0; i < raw.Length; i++)
{
raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
}
return raw;
}
}
See it in action in a fiddle here:
https://dotnetfiddle.net/axUC5n
Hope this helps and good luck with your project
You should most probably use Encoding.Unicode to convert the string to a byte array: it's quite possible that some characters cannot be represented by ASCII chars.
Encoding.Unicode (UTF-16LE) always uses 2 bytes, so it's predictable: a sequence of 4 chars in the HEX string will always represent an UFT-16 CodePoint.
No matter what characters the input string contains.
Convert string to HEX:
string input = "Yourstring \"Ваша строка\"{あなたのひも},آپ کی تار";;
string hex = string.Concat(Encoding.Unicode.GetBytes(input).Select(b => b.ToString("X2")));
Convert back to string:
var bytes = new List<byte>();
for (int i = 0; i < hex.Length; i += 2) {
bytes.Add(byte.Parse(hex.Substring(i, 2), NumberStyles.HexNumber));
}
string original = Encoding.Unicode.GetString(bytes.ToArray());
How can I convert array[1] to hexadecimal in C#
array[1] = 1443484
I have tried the following but it doesn't compile:
StringBuilder hex = new StringBuilder(array[1].Length * 2);
foreach (byte b in array[1])
hex.AppendFormat("{0:x2}", b);
string value = hex.ToString();
If you want just to obtain hexadecimal representation, you can do it in one go:
// 16069c
string value = Convert.ToString(array[1], 16);
Or
string value = array[1].ToString("x");
Or (padded version: at least 8 characters)
// 0016069c
string value = array[1].ToString("x8");
If you want to manipulate with bytes try BitConverter class
byte[] bytes = BitConverter.GetBytes(array[1]);
string value = string.Concat(bytes.Select(b => b.ToString("x2")));
Your code amended:
using System.Runtime.InteropServices; // For Marshal
...
// Marshal.SizeOf - length in bytes (we don't have int.Length in C#)
StringBuilder hex = new StringBuilder(Marshal.SizeOf(array[1]) * 2);
// BitConverter.GetBytes - byte[] representation
foreach (byte b in BitConverter.GetBytes(array[1]))
hex.AppendFormat("{0:x2}", b);
// You can well get "9c061600" (reversed bytes) instead of "0016069c"
// if BitConverter.IsLittleEndian == true
string value = hex.ToString();
I have an array of integer 1s and 0s (possibly need to get converted to byte type?). I have used an online ASCII to binary generator to get the equivalent binary of this 6 digit letter sequence:
abcdef should equal 011000010110001001100011011001000110010101100110 in binary. So in c#, my array is [0,1,1,0,0,0,0...], built by:
int[] innerArr = new int[48];
for (int i = 0; i < 48); i++) {
int innerIsWhite = color.val[0] > 200 ? 0 : 1;
innerArr[i] = innerIsWhite;
}
I want to take this array, and convert it into abcdef (and be able to do the opposite).
How do I do this? Is there a better way to be storing these ones and zeros.
Try using Linq and Convert:
source = "abcdef";
// 011000010110001001100011011001000110010101100110
string encoded = string.Concat(source
.Select(c => Convert.ToString(c, 2).PadLeft(8, '0')));
// If we want an array
byte[] encodedArray = encoded
.Select(c => (byte) (c - '0'))
.ToArray();
// string from array
string encodedFromArray = string.Concat(encodedArray);
// abcdef
string decoded = string.Concat(Enumerable
.Range(0, encoded.Length / 8)
.Select(i => (char) Convert.ToByte(encoded.Substring(i * 8, 8), 2)));
If your input is a bit string, then you can use a method like below to convert that into character string
public static string GetStringFromAsciiBitString(string bitString) {
var asciiiByteData = new byte[bitString.Length / 8];
for (int i = 0, j = 0; i < asciiiByteData.Length; ++i, j+= 8)
asciiiByteData[i] = Convert.ToByte(bitString.Substring(j, 8), 2);
return Encoding.ASCII.GetString(asciiiByteData);
}
The above code simply uses the Convert.ToByte method asking it to do a base-2 string to byte conversion. Then using Encoding.ASCII.GetString, you get the string representation from the byte array
In my code, I presume your bit string is clean (multiple of 8 and with only 0s and 1s), in production grade code you will have to sanitize your input.
I have a byte array:
newMsg.DATA = new byte[64];
How can I convert it into binary value and then write it in text file with comma separation. Comma should be in between binary values not bytes.....
like 1,1,1,0,0,0,1,1,1,1,1,0,0,0,0,0.......
Here is an example that uses LINQ:
byte[] arr = new byte[] { 11, 55, 255, 188, 99, 22, 31, 43, 25, 122 };
string[] result = arr.Select(x => string.Join(",", Convert.ToString(x, 2)
.PadLeft(8, '0').ToCharArray())).ToArray();
System.IO.File.WriteAllLines(#"D:\myFile.txt", result);
Every number in byte[] arr is converted to a binary number with Convert.ToString(x, 2) and the comma "," is added between binary values with string.Join(",",...). At the end you can write all the elements in result to a text file by using System.IO.File.WriteAllLines.
The example above gives you this kind of output in a txt file:
0,0,0,0,1,0,1,1
0,0,1,1,0,1,1,1
1,1,1,1,1,1,1,1
...
Explanation of Convert.ToString(value, baseValue):
The first parameter value represents the number you want to convert to a string
and the second parameter baseValue represents which type of conversion you want to perform.
Posible baseValues are : 2,8,10 and 16.
BaseValue = 2 - represents a conversion to a binary number representation.
BaseValue = 8 - represents a conversion to a octal number representation.
BaseValue = 10 - represents a conversion to a decimal number representation.
BaseValue = 16 - represents a conversion to a hexadecimal number representation.
I think this will Help you c# provides inbuilt functionality to do so
with help of Convert.ToString(byte[],base); here base could be[2(binary),8(octal),16(HexaDecimal)]
byte[] data = new byte[64];
// 2nd parameter 2 is Base e.g.(binary)
string a = Convert.ToString(data[data.Length], 2);
StringBuilder sb = new StringBuilder();
foreach(char ch in a.ToCharArray())
{
sb.Append(ch+",");
}
// This is to remove last extra ,
string ans = sb.ToString().Remove(sb.Length - 1, 1);
This should get you going:
var bytes = new byte[] { 128, 255, 2 };
var stringBuilder = new StringBuilder();
for (var index = 0; index < bytes.Length; index++)
{
var binary = Convert.ToString(bytes[index], 2).PadLeft(8, '0');
var str = string.Join(",", binary.ToCharArray());
stringBuilder.Append(str);
if (index != bytes.Length -1) stringBuilder.Append(",");
}
Console.WriteLine(stringBuilder);
i need to decode a string in C#. Algorithm peformed in HEX values. So in C# i think i need to convert to byte array?am i right?. So I did a byte array from a string:
string Encoded = "ENCODEDSTRINGSOMETHING";
byte[] ba = Encoding.Default.GetBytes (Encoded);
Now i need to modify each byte in byte array first starting from summing hex value (0x20) to first byte and for the each next byte in array i should substitute 0x01 hex from starting 0x20 hex value and sum it with following bytes in my ba array. Then i need to convert my byte array result to string again and print. In Python this is very easy:
def decode ():
strEncoded = "ENCODEDSTRINGSOMETHING"
strDecoded = ""
counter = 0x20
for ch in strEncoded:
ch_mod = ord(ch) + counter
counter -= 1
strDecoded += chr(ch_mod)
print ("%s" % strDecoded)
if __name__ == '__main__':
decode()
How can i do it in C#? Thank you very much.
Here's a rough outline of how to do what you are trying to do. Might need to change it a bit to fit your problem/solution.
public string Encode(string input, int initialOffset = 0x20)
{
string result = "";
foreach(var c in input)
{
result += (char)(c + (initialOffset --));
}
return result;
}
Try this code:
string Encoded = "ENCODEDSTRINGSOMETHING";
byte[] ba = Encoding.Default.GetBytes(Encoded);
string strDecoded = "";
int counter = 0x20;
foreach (char c in Encoded)
{
int ch_mod = (int)c+counter;
counter -= 1;
strDecoded += (char)ch_mod;
}