1

I would like to generate the (hex?) string representation of a C# byte[] of some object to be able to bulk imported into a varbinary field. When I use:

System.Text.Encoding.UTF8.GetString(X);

I am getting strings that look like this:

????N4?V?tw?c??*???9

rather than what I see when I do a select statement:

0x016C9562F6C8ACE9B25F12788E571C0CA04C2C1F4F7353F849E8199471DB18DC

Of course, this might just be a text editor issue.

Any ideas what to use in C# to be able to generate strings for bulk importing the string representation of the data into varbinary fields?

6
  • Do you want to create an insert script with this hex string in it or do you want to do the insert operation out of your C# application? Commented Mar 17, 2016 at 17:23
  • Could you please clarify exactly what output you expect? Commented Mar 17, 2016 at 19:03
  • @Shnugo I want ti create the hex string to run a bulk import via sql.
    – cs0815
    Commented Mar 17, 2016 at 21:21
  • Try to quick-watch/ debug your bytearray content and compare with the 0x version without text-encoding it. Commented Mar 18, 2016 at 9:19
  • Why varbinary at all? Why convert a Unicode string to something else when SQL Server already supports Unicode? If you are trying to store Unicode text, why not use nvarchar or nvarchar(max)? Commented Mar 18, 2016 at 9:23

1 Answer 1

2

There's already several answers like this on getting HEX from a string, in your case, you mention that your original value is a Byte[] and here's some test:

assuming:

var s = "helloWorld";
var sB = System.Text.Encoding.UTF8.GetBytes(s);

you will get 00680065006C006C006F0057006F0072006C0064 using

string.Join("", sB.Select(c => String.Format("{0:X4}", Convert.ToInt32(c))));

or 68656C6C6F576F726C64 using

string.Join("", sB.Select(c => String.Format("{0:X2}", Convert.ToInt32(c))));

several other answers let you convert the HEX into String again, if you ever need it...

1
  • I just realized that it is actually just a question to transform the bytes to hex (-: sorry but thanks for your answer.
    – cs0815
    Commented Mar 18, 2016 at 12:00

Not the answer you're looking for? Browse other questions tagged or ask your own question.