简体   繁体   中英

How to convert int into Byte Array?

I have a table in which there is one column named:

'eZip' (varbinary(5), null).

Now I am adding value from a web form like this:

 cmd.Parameters.Add("@eZip", SqlDbType.VarBinary).Value = BitConverter.GetBytes(int.Parse(txtZip.Text.ToString()));

Its working but instead of putting a valid zip code, it is inserting this into my column:

<Binary data>

What I am doing wrong here?

I don't think you are doing anything wrong per-se. if you define the field as varbinary you will always see "Binary Data" in SQL Server's management tools, regardless of the data.

Are you sure you don't want just CHAR(n) OR VARCHAR(n) for the zip code?

If you can't change the data type of that column, all you need to do is convert the value when you get the data back out. As recommended by others, you should at least change your code to assume that the five bytes are characters, not integers.

Insert the value:

 cmd.Parameters.Add("@eZip", SqlDbType.VarBinary).Value = System.Text.Encoding.ASCII.GetBytes(txtZip.Text.ToString()); 

Retrieve the value in SSMS tools:

SELECT CONVERT(VARCHAR(5), [eZip]) AS [eZip] FROM @zip_table;

Retrieve the value from a DataRow dr in C#:

System.Text.Encoding.ASCII.GetString(dr["eZip"]);

If you can change the column to a CHAR(5) or VARCHAR(5), then no conversion will be necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM