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?

cs0815
  • 16,751
  • 45
  • 136
  • 299
  • 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? – Shnugo Mar 17 '16 at 17:23
  • Could you please clarify exactly what output you expect? – Mads Nielsen Mar 17 '16 at 19:03
  • @Shnugo I want ti create the hex string to run a bulk import via sql. – cs0815 Mar 17 '16 at 21:21
  • Try to quick-watch/ debug your bytearray content and compare with the 0x version without text-encoding it. – Allan S. Hansen Mar 18 '16 at 09: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)`? – Panagiotis Kanavos Mar 18 '16 at 09:23
  • As for the actual problem, what is the input string? And how did you try to store the byets? `?` appears when there is a conversion problem between *codepages*, typically avoided by *not* using codepages. – Panagiotis Kanavos Mar 18 '16 at 09:25

1 Answers1

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...

Community
  • 1
  • 1
balexandre
  • 73,608
  • 45
  • 233
  • 342
  • I just realized that it is actually just a question to transform the bytes to hex (-: sorry but thanks for your answer. – cs0815 Mar 18 '16 at 12:00