Reputation: 21312
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?
Upvotes: 1
Views: 3103
Reputation: 887415
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);
}
Upvotes: 1
Reputation: 269368
string forDisplay = "0x" + BitConverter.ToString(yourByteArray).Replace("-", "");
Upvotes: 4