We are store string values in a database using varBinary type using c# and BinaryFormatter.We convert to byte array and then we save to DataBase
public static byte[] ToBytes(stringvalue)
{
if (value == null)
return null;
byte[] inMemoryBytes;
using (MemoryStream inMemoryData = new MemoryStream())
{
new BinaryFormatter().Serialize(inMemoryData, value);
inMemoryBytes = inMemoryData.ToArray();
}
return inMemoryBytes;
}
OK, So if we save char "a", we can see "0x0001000000FFFFFFFF0100000000000000060100000001610B" in the database.After we can retrieve the data and convert again to string.
Can we convert this binary value ("0x0001000000FFFFFFFF0100000000000000060100000001610B") to char ("a") only using transact SQL (so we can do modifications, inserts, comparations from sql server console)?
Thanks a lot.
You can choose from several encoding options to convert a byte array into a string: Encoding.ASCII: Gets an encoding for the ASCII (7-bit) character set. Encoding.BigEndianUnicode: Gets an encoding for the UTF-16 format using the big-endian byte order. Encoding.Default: Gets an encoding for the system's current ANSI code page.
Though, we should use charset for decoding a byte array. There are two ways to convert byte array to String: By using String class constructor; By using UTF-8 encoding; By using String Class Constructor. The simplest way to convert a byte array into String, we can use String class constructor with byte[] as the constructor argument.
Since bytes is the binary data while String is character data. It is important to know the original encoding of the text from which the byte array has created. When we use a different character encoding, we do not get the original string back. Suppose, we have to read byte array from a file which is encoded in " ISO_8859_1 ".
We convert the data in the table into JSON using the built-in hint " FOR JSON AUTO ". This operating will automatically convert any binary data type in the table into BASE64 String. Next, Using the function OPENJSON, we extract the BASE64 String from the JSON
You could to use something simpler, as
Encoding.Default.GetBytes("a");
That will return "61" and can be more easily translated to a varchar, just running this:
create table #sample (content varbinary(max));
insert into #sample values (0x61)
select cast(content as varchar) from #sample
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With