2011-05-23 7 views
5

Jestem w kontekście javascript po stronie klienta. Mam GUID w formacie strunowym e8b75aff-3422-4529-8a6a-15b33e674f48 i potrzebuję go w łańcuchu Base64/1q36CI0KUWKahWzPmdPSA== Jak mogę go przekonwertować?JavaScript przekonwertuj identyfikator GUID w formacie string na Base64

Dzięki.

+0

możliwe duplikat [Jak można zakodować do Base64 przy użyciu JavaScript?] (Http://stackoverflow.com/questions/246801/how-can-you-encode-to-base64 -using-javascript) –

+1

możliwy duplikat http://stackoverflow.com/q/246801/49186 – dexter

+0

Co na ten temat: http://stackoverflow.com/questions/2058732/how-can-i-converta-a- Guid-to-a-byte-array-in-javascript – mplungjan

Odpowiedz

7

// Convert GUID string to Base-64 in Javascript 
 
// by Mark Seecof, 2012-03-31 
 

 
var hexlist = 'abcdef'; 
 
var b64list = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/'; 
 

 
// GUID string with four dashes is always MSB first, 
 
// but base-64 GUID's vary by target-system endian-ness. 
 
// Little-endian systems are far more common. Set le==true 
 
// when target system is little-endian (e.g., x86 machine). 
 
// 
 
function guid_to_base64(g, le) { 
 
    var s = g.replace(/[^0-9a-f]/ig, '').toLowerCase(); 
 
    if (s.length != 32) return ''; 
 

 
    if (le) s = s.slice(6, 8) + s.slice(4, 6) + s.slice(2, 4) + s.slice(0, 2) + 
 
     s.slice(10, 12) + s.slice(8, 10) + 
 
     s.slice(14, 16) + s.slice(12, 14) + 
 
     s.slice(16); 
 
    s += '0'; 
 

 
    var a, p, q; 
 
    var r = ''; 
 
    var i = 0; 
 
    while (i < 33) { 
 
     a = (hexlist.indexOf(s.charAt(i++)) << 8) | 
 
     (hexlist.indexOf(s.charAt(i++)) << 4) | 
 
     (hexlist.indexOf(s.charAt(i++))); 
 

 
     p = a >> 6; 
 
     q = a & 63; 
 

 
     r += b64list.charAt(p) + b64list.charAt(q); 
 
    } 
 
    r += '=='; 
 

 
    return r; 
 
    } // guid_to_base64() 
 

 
//EDIT 
 
function tryConversion() { 
 
    document.getElementById("result").innerText = guid_to_base64(
 
    document.getElementById("input_guid").value, 
 
    document.getElementById("cb_le").checked 
 
); 
 
}
input[type=text] { 
 
    font-family: monospace; 
 
    font-size: 12px; 
 
    width: 270px; 
 
}
<div><label for="input_guid">GUID</label> <input type="text" maxlength="36" id="input_guid" value="83D95782-BDE4-466F-A490-46820D2B2CDC" /> 
 
</div> 
 
<div><label for="cb_le">Little-Endian?</label> <input type="checkbox" id="cb_le" checked="checked" /></div> 
 
<hr /> 
 
<div><button onclick="javascript:tryConversion()">Convert</button></div> 
 
<div>Result: <span id="result"></span></div>