byte 與string相互轉換

2021-05-24 21:49:53 字數 1461 閱讀 3446

c#中byte與string相互轉換及string與sql server中nvarchar的轉換問題

最近在寫專業實踐-資料庫加密,找出以前寫的md5、des程式,編成兩個動態鏈結庫md5.dll、des.dll,在這把我遇到的問題分享下~

(1)byte與string的相互轉換

首先在c#中string是unicode編碼,byte是8位無符號整數,而char是16位的,如何將string轉換成byte,將其作為引數 呼叫dll計算md5值或是des加密?獲得加密結果(byte型別)後,將其轉換成string型別存入資料庫(sql server 2000)中,同時又能從資料庫中讀出並轉換成原來的byte呢?

public byte ascstringtobytearray(string s)

public string ascbytearraytostring(byte b)

public byte unistringtobytearray(string s)

public string unibytearraytostring(byte b)

看了這個就知道了,byte轉string有兩種編碼方式:ascii和unicode,其中在ascii編碼下,string的每個字元都轉換其相 應的ascii值,對應乙個byte,而在unicode編碼下,string的每個字元要轉換成兩個byte,因此

如果在ascii編碼下byte(byte大小為0-255)轉換成string時可能會發生溢位。

當你需要長度為8的string轉換成byte[8]時,例如呼叫dll時函式引數為byte[8],這個時候就可以用ascstringtobytearray(),同時在解密後,要將byte[8]轉換成8位的string,

這時可以確認byte[8]中的byte的值都在(0,127)內,

因此可以放心地用ascbytearraytostring()轉換而不會發生溢位。

但是當加密後的結果需要以string形式存入sql server時,加密結果的byte[16]就需要用unibytearraytostring()轉換成長度為8的string,同時長度為8的 string用unistringtobytearray()可以轉換成原來的byte[16],

因為如果用ascii編碼,可以肯定轉換不回去。

(2)string與sql server中的nvarchar訪問的亂碼問題

問題又來了,當string存入sql server 2000是,雖然相應的字段設成

nvarchar型別,

可是開啟資料庫一看卻有亂碼和問號 ,讀出資料來看,還是亂碼和問號。原來 unicode的string在存入資料庫時需要用到關鍵字

n,例如:

string sql = string.format("insert into [user] values('" + username + "',n'"+password + "')");

呵呵,這下總算沒問題了吧!下篇寫寫資料庫加密的實現,先完善我的程式吧!

bitmapimage與byte 相互轉換

wpf image byte wpf bitmapimage 有時要實現bitmapimage與byte相互轉換,這裡實現兩個靜態方法,直接呼叫即可。byte轉換為bitmapimage public static bitmapimage bytearraytobitmapimage byte by...

C 下byte陣列與string的相互轉換

1,string字串轉化為byte陣列,ascii碼格式。源 如下 c sharp view plain copy 定義變數 byte temp string strtemp 你好 int ilen 0 轉換 temp new asciiencoding getbytes strtemp 得到轉換後...

String 與string的相互轉換

採用了c 呼叫c dll的方法,在.net中string是需要用gcnew進行初始化,先來看看gcnew和普通的new的區別 c cli中使用gcnew關鍵字表示在託管堆上分配記憶體,並且為了與以前的指標區分,用 來替換 就語義上來說他們的區別大致如下 1.gcnew返回的是乙個控制代碼 handl...