From: 011netservice@gmail.com Date: 2022-04-24 Subject: UnicodeStringToHex.txt 歡迎來信交流. ---------- Javascript: Unicode string to hex https://stackoverflow.com/questions/21647928/javascript-unicode-string-to-hex Remember that a JavaScript code unit is 16 bits wide. Therefore the hex string form will be 4 digits per code unit. usage: var str = "\u6f22\u5b57"; // "\u6f22\u5b57" === "漢字" alert(str.hexEncode().hexDecode()); String to hex form: String.prototype.hexEncode = function(){ var hex, i; var result = ""; for (i=0; i /// Convert a string to hex value /// /// /// public string HexEncode(string stringValue) { var ba = Encoding.Unicode.GetBytes(stringValue); // SOLUTION 1 //var c = new char[ba.Length * 2]; //for (var i = 0; i < ba.Length; i++) //{ // var b = ba[i] >> 4; // c[i * 2] = (char)(55 + b + (((b - 10) >> 31) & -7)); // b = ba[i] & 0xF; // c[i * 2 + 1] = (char)(55 + b + (((b - 10) >> 31) & -7)); //} //return new string(c); // SOLUTION 2 var hex = new StringBuilder(ba.Length * 2); foreach (var b in ba) hex.AppendFormat("{0:x2}", b); return hex.ToString(); } /// /// Converts a hex value to a string /// /// /// public string HexDecode(string hexString) { if (hexString == null || (hexString.Length & 1) == 1) return ""; // SOLUTION 1 //hexString = hexString.ToUpper(); //var hexStringLength = hexString.Length; //var b = new byte[hexStringLength / 2]; //for (var i = 0; i < hexStringLength; i += 2) //{ // var topChar = (hexString[i] > 0x40 ? hexString[i] - 0x37 : hexString[i] - 0x30) << 4; // var bottomChar = hexString[i + 1] > 0x40 ? hexString[i + 1] - 0x37 : hexString[i + 1] - 0x30; // b[i / 2] = Convert.ToByte(topChar + bottomChar); //} // SOLUTION 2 var numberChars = hexString.Length; var bytes = new byte[numberChars / 2]; for (var i = 0; i < numberChars; i += 2) bytes[i / 2] = Convert.ToByte(hexString.Substring(i, 2), 16); return Encoding.Unicode.GetString(bytes); } var hex = tools.HexEncode("그러하지"); var str = tools.HexDecode(hex); // f8adecb758d5c0c9 JS:adf8 b7ec d558 c9c0 C#:f8ad ecb7 58d5 c0c9 這樣就交換了序列。 只要我在同一環境中,編碼和解碼都可以工作。但是我需要用JS編碼和C#解碼,反之亦然。 我不知道哪一個是正確的,如果可以在這裡定義正確的話。 我該如何解決呢? 解決辦法 這兩個值都是正確的。只是您的javascript解決方案為您提供了Big Endian表示法的unicode陣列, 以及Little Endian的C#-(MSDN article,請參見“備註”部分)。 要使C#位元組陣列與javascript相同,請定義您的編碼,如下所示: UnicodeEncoding bigEndianUnicode = new UnicodeEncoding(true, true); 然後像這樣使用它: var ba = bigEndianUnicode.GetBytes(stringValue);