I'm trying to convert a string with modified GUID (e.g. 6b5737e5728786794fff5e009d74d706) to a hex string with format like \x..\x..
(String format and hex chars doesn't work for me). Any ideas?
Regex.Replace(myString, ".{2}", "\\x$0");
If you want to go a non-regex route, then the following might work:
string s = "6b5737e5728786794fff5e009d74d70";
var sb = new StringBuilder($s.Length * 2);
for (int i = 0; i < s.Length; i+=2)
sb.Append("\\x").Append(s.Substring(i, [Math]::Min(2, s.Length - i)));
string myNewString = sb.ToString();
If you want your string to contain (for your example) the code points U+006B, U+0057, U+0037, &c. then think again please. Strings are no byte containers, they are text containers. You want a byte[] in that case:
byte[] byteArray = new byte[(s.Length + 1) / 2]
for (int i = 0; i < s.Length; i+=2)
byteArray[i/2] = Convert.ToByte(s.Substring(i, [Math]::Min(2, s.Length - i)));
Related
I have written this piece of code:
int i = 0;
br.BaseStream.Position = i;
armorvalues[i] = br.ReadBytes(0x000E91D4);
string[] outbyte= new string[0x000E91D4];
for (int j=0; j < 0x000E91D4; j++)
{
outbyte[j] = Convert.ToString(String.Format("{0:X2}", armorvalues[0][j]));
}
Now since this is an array and I want to some algorithmic operations on the whole data, I need to convert it into a string. i need to append it in a single string. What should I do?
Not sure why you want to do so, maybe if you explain better your need then it'll be good. But for your question:
You can use string.Join:
var strValue = string.Join(" ", outbyte);
And instead of doing it after the look you can also:
var strValue = string.Join(" ", armorvalues[0].Select(item => String.Format("{0:X2}", item)));
Take a look at the StringBuilder class
StringBuilder sb = new StringBuilder(0x000E91D4*2); // length * 2 since every byte is going to be represented by 2 chars
for (int j=0; j < 0x000E91D4; j++)
{
sb.Append(Convert.ToString(String.Format("{0:X2}", armorvalues[0][j])));
}
string yourString = sb.ToString();
Edit:
I was not aware of that string.Join overload that takes an IEnumerable, that it more elegant, go with Gilad Green's solution or if you don't want the values be separated by an empty space (" ") just do
string output = string.Concat(armorvalues[0].Select(item => String.Format("{0:X2}", item)));
G'day,
I have a char array that varies in size based on the length of some data. The array will never be larger than 24 though. It may however, be less than 24. As a result of this I need to "pad left" with 0's, as in add more elements to the left of the array to make it 24. I have below some code that does this, just wondering if there is a faster way or more efficient way to do so. Thanks!
Note: I don't think this is a duplicate as I am working with char[]'s not strings.
char[] dataLen = Convert.ToString(data.Length, 2).ToCharArray();
int j = 0;
char[] tmp = new char[24];
for (int i = 0; i < 24; i++)
{
if (i < (24 - dataLen.Length))
tmp[i] = '0';
else
tmp[i] = dataLen[j++];
}
dataLen = tmp;
Why don't you simply use String.PadLeft?
char[] data = "abcdefgh".ToCharArray(); // sample data
data = new string(data).PadLeft(24, '0').ToCharArray();
That should be efficient and is also very readable.
how about :
string z24 = "000000000000000000000";
tmp = z24.Take(24 - dataLen.Length).Union(dataLen).ToArray();
I would simply use a string for all operations, and use PadLeft to do the padding.
string input = new string(data);
string result = input.PadLeft(24, '0');
Then convert it to a char[] if you really need to:
char[] chars = result.ToCharArray();
(Also, your Convert.ToString(data.Length, 2) doesn't return their string representation, new string(data) does)
Hi I'm developing an client application in C# and the server is written in c++
the server uses:
inline void StrToInts(int *pInts, int Num, const char *pStr)
{
int Index = 0;
while(Num)
{
char aBuf[4] = {0,0,0,0};
for(int c = 0; c < 4 && pStr[Index]; c++, Index++)
aBuf[c] = pStr[Index];
*pInts = ((aBuf[0]+128)<<24)|((aBuf[1]+128)<<16)|((aBuf[2]+128)<<8)|(aBuf[3]+128);
pInts++;
Num--;
}
// null terminate
pInts[-1] &= 0xffffff00;
}
to convert an string to int[]
in my c# client i recieve:
int[4] { -14240, -12938, -16988, -8832 }
How do I convert the array back to an string?
I don't want to use unsafe code (e.g. pointers)
Any of my tries resulted in unreadable strings.
EDIT:
Here is one of my approch:
private string IntsToString(int[] ints)
{
StringBuilder s = new StringBuilder();
for (int i = 0; i < ints.Length; i++)
{
byte[] bytes = BitConverter.GetBytes(ints[i]);
for (int j = 0; j < bytes.Length; j++)
s.Append((char)(bytes[j] & 0x7F));
}
return s.ToString();
}
I know I need to take care of endianess but as the server is running on my local machine and the server too, I assume that this is not a problem.
My other try was to use an struct with explicit layout and same FieldOffset for integer and chars but it doesn't work, either.
Maybe try something like (using LINQ):
int[] fromServer = { -14240, -12938, -16988, -8832, };
string reconstructedStr = new string(fromServer.SelectMany(BitConverter.GetBytes).Select(b => (char)(b - 128)).ToArray());
Untested, but there's something to start from. Don't know if the subtraction of 128 is correct.
You can create a comma separated string this way:
string str = String.Join(", ", intArray.Select(x => x.ToString()).ToArray());
var ints = new[] {-14240, -12938, -16988, -8832};
var result = string.Join("-", ints.Select(i => BitConverter.ToString(BitConverter.GetBytes(i))));
Console.WriteLine(result); //60-C8-FF-FF-76-CD-FF-FF-A4-BD-FF-FF-80-DD-FF-FF
BitConverter.ToString can be replaced by something else here, depending on how you will parse string later.
Is there a built in .NET function or an easy way to convert from:
"01234"
to:
"\u2070\u00B9\u00B2\u00B3\u2074"
Note that superscript 1, 2 and 3 are not in the range \u2070-\u209F but \u0080-\u00FF.
EDIT: I hadn't noticed that the superscript characters weren't as simple as \u2070-\u2079. You probably want to set up a mapping between characters. If you only need digits, you could just index into a string fairly easily:
const string SuperscriptDigits =
"\u2070\u00b9\u00b2\u00b3\u2074\u2075\u2076\u2077\u2078\u2079";
Then using LINQ:
string superscript = new string(text.Select(x => SuperscriptDigits[x - '0'])
.ToArray());
Or without:
char[] chars = text.ToArray();
for (int i = 0; i < chars.Length; i++)
{
chars[i] = SuperscriptDigits[chars[i] - '0'];
}
string superscript = new string(chars);
I have an image data type in my table. When I query using SQL Server Management Studio, I get the following in my results window, both grid and text.
0x255044462D312E320D0A0D0A332030206F[Truncated for Length]
I am attempting to replicate this in a little c# program.
However, when I use either SqlCommand or LINQ I get the output:
JVBERi0xLjINCg0KMyAwIG9iag0KPDwNCi9FIDIxODgyDQovSCBbIDExNTAgMTUxIF0NCi9MIDIyM[TRUNCATED]
Any thoughts to what I need to do to get the 0x25... output to display? I have tried doing byte[] conversions and Encoding, but can't seem to find the right one.
If I am not clear, please let me know.
Edit:
I am not trying to display the image, just the 0x25...
Thoughts?
string forDisplay = "0x" + BitConverter.ToString(yourByteArray).Replace("-", "");
AFAIK, .Net does not include any methods to print an arbitrary byte array as a single hex number. (Until .Net 4.0's System.Numerics.BigInteger)
However, you should be able to write
"0x" + BitConverter.ToString(bytes).Replace("-", "")
Note that this is incredibly inefficient; if you want to do this in real code, use a StringBuilder in a loop. EDIT: Like this:
public static string ToHexString(this byte[] bytes) {
var builder = new StringBuilder(bytes.Length * 2 + 2);
builder.Append("0x");
for (int i = 0; i < bytes.Length; i++)
builder.Append(bytes[i].ToString("X2"));
return builder.ToString();
}
2nd EDIT: Here's a new version which really is faster. (Yes, I know you don't need it; here it is anyway)
private static char ToHexDigit(int i) {
if (i < 10)
return (char)(i + '0');
return (char)(i - 10 + 'A');
}
public static string ToHexString(byte[] bytes) {
var chars = new char[bytes.Length * 2 + 2];
chars[0] = '0';
chars[1] = 'x';
for (int i = 0; i < bytes.Length; i++) {
chars[2 * i + 2] = ToHexDigit(bytes[i] / 16);
chars[2 * i + 3] = ToHexDigit(bytes[i] % 16);
}
return new string(chars);
}