SQL Image DataType - C# Display Output - c#

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);
}

Related

Getting System.Char[] instead of value

I'm trying to convert double to binary, but when I run my project, I get System.Char[] in my text box instead of binary values. How can I solve this problem?
int bitCount = sizeof(float) * 8;
char[] result = new char[bitCount];
int intValue = System.BitConverter.ToInt32(BitConverter.GetBytes(testvalue), 0);
for (int bit = 0; bit < bitCount; ++bit)
{
int maskedValue = intValue & (1 << bit);
if (maskedValue > 0)
maskedValue = 1;
result[bitCount - bit - 1] = maskedValue.ToString()[0];
}
new string(result);
richTextBox1.Text = richTextBox1.Text+"\n"+result;
// pictureBox2.Image = bmp;
new string(result);
This is the problem. You do not assign this to any variable. I believe you should use it instead of result when you assing to textbox.Text.
You get System.Char[] in your text box, because ToString() for char arrays returns such a string.
So try following:
String resultString = new string(result);
richTextBox1.Text = richTextBox1.Text + Environment.NewLine + resultString;

int[] to string c#

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.

Covert string to hexdecimal string with format "\x..\x.."?

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)));

C# hex to ascii

I'm trying to convert a String of hex to ASCII, using this:
public void ConvertHex(String hexString)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hexString.Length; i += 2)
{
String hs = hexString.Substring(i, i + 2);
System.Convert.ToChar(System.Convert.ToUInt32(hexString.Substring(0, 2), 16)).ToString();
}
String ascii = sb.ToString();
MessageBox.Show(ascii);
}
but I get an out or bounds exception, I'm sure its a glaring error but other code I have tried does not work either. What am I doing wrong?
This code will convert the hex string into ASCII, you can copy paste this into a class and use it without instancing
public static string ConvertHex(String hexString)
{
try
{
string ascii = string.Empty;
for (int i = 0; i < hexString.Length; i += 2)
{
String hs = string.Empty;
hs = hexString.Substring(i,2);
uint decval = System.Convert.ToUInt32(hs, 16);
char character = System.Convert.ToChar(decval);
ascii += character;
}
return ascii;
}
catch (Exception ex) { Console.WriteLine(ex.Message); }
return string.Empty;
}
Notes
2 = the no. of hexString chars used to represent an ASCII character.
System.Convert.ToUInt32(hs, 16) = "convert the base 16 hex substrings to an unsigned 32 bit int"
There are four three problems here:
Since you're incrementing i by 2 on each iteration, you need to terminate at hexString.Length - 1. This doesn't actually matter; incrementing by two after the final iteration will bring the counter above the checked length regardless.
You're taking the wrong number of characters from hexString.
hs is never used.
You're not appending anything to sb.
Try this:
for (int i = 0; i < hexString.Length; i += 2)
{
string hs = hexString.Substring(i, 2);
sb.Append(Convert.ToChar(Convert.ToUInt32(hs, 16)));
}
Note that there's no need to qualify the types with their namespace, System (assuming you've referenced it at the top of the file with a using statement).
String hs = hexString.Substring(i, i + 2);
System.Convert.ToChar(System.Convert.ToUInt32(hexString.Substring(0, 2), 16)).ToString();
Do you notice you're never using hs ??
And that you're converting the first 2 chars over and over?
Since you are incrementing your index by 2, you need to stop your loop one-before-the-end of the length of the string. Otherwise your last iteration of the loop will try to read characters past the end of the string.
for (int i = 0; i < hexString.Length - 1, i += 2)

Editing a line in a text file without using pointers?

I am trying to edit a line of a text file (.Hex file) containing all Hex characters without using pointers and in a more efficient way.
It takes so long because the program I have to edit some (around 30x4 bytes or 30 float values from the address values of hex file).
Every time the program replaces one byte, it searches the complete file and replaces the values, and copy back back again the new file to another file. This process repeats 30 times, which is quite time consuming and hence not looks appropriate.
What would be the most efficient method?
public static string putbyteinhexfile(int address, char data, string total)
{
int temph, temphl, tempht;
ushort checksum = 0;
string output = null, hexa = null;
StreamReader hex;
RegistryKey reg = Registry.CurrentUser;
reg = reg.OpenSubKey("Software\\Calibratortest");
hex = new StreamReader(((string)reg.GetValue("Select Input Hex File")));
StreamReader map = new StreamReader((string)reg.GetValue("Select Linker Map File"));
while ((output = hex.ReadLine()) != null)
{
checksum = 0;
temph = Convert.ToInt16(("0x" + output.Substring(3, 4)), 16);
temphl = Convert.ToInt16(("0x" + output.Substring(1, 2)), 16);
tempht = Convert.ToInt16(("0x" + output.Substring(7, 2)), 16);
if (address >= temph &&
address < temph + temphl &&
tempht == 0)
{
output = output.Remove((address - temph) * 2 + 9, 2);
output = output.Insert((address - temph) * 2 + 9,
String.Format("{0:X2}", Convert.ToInt16(data)));
for (int i = 1; i < (output.Length - 1) / 2; i++)
checksum += (ushort)Convert.ToUInt16(output.Substring((i * 2) - 1, 2), 16);
hexa = ((~checksum + 1).ToString("x8")).ToUpper();
output = output.Remove(temphl * 2 + 9, 2);
output = output.Insert(temphl * 2 + 9,
hexa.Substring(hexa.Length - 2, 2));
break;
}
else total = total + output + '\r' + '\n';
}
hex.Close();
map.Close();
return total;
}
Assuming you don't want to massively rewrite your existing logic which does 'for each line, do this search and replace logic', I'd think the simplest change would be:
var lines = File.ReadAllLines(filePath);
foreach (change to make)
{
for (int i = 0; i < lines.Length; i++)
{
// read values from line
if (need_to_modify)
{
// whatever change logic you want here.
lines[i] = lines[i].Replace(...);
}
}
}
File.WriteAllLines(filePath, lines);
Basically, you'll still do the logic you have now, except:
You read the file once instead of N times
you get rid of streamreader / streamwriter work
you do your changes on the array of strings in memory
string fileName = "blabla.hex";
StreamReader f1 = File.OpenText(fileName);
StreamWriter f2 = File.CreateText(fileName + ".temp_");
while (!f1.EndOfStream)
{
String s = f1.ReadLine();
//change the content of the variable 's' as you wish
f2.WriteLine(s);
}
f1.Close();
f2.Close();
File.Replace(fileName + ".temp_", fileName, null);

Categories