js字符与ASCII码互转的方法

2023-12-22 12:34:05
  • 字符 to ASCII码
	var str="A"
	var c = str.charCodeAt()
	console.log('A = ',str.charCodeAt());//65
  • ASCII码 to 字符
var s = String.fromCharCode(0x41)//0x41=65,直接填65是一样的
console.log('s = ',s);//A
  • int类型 to 字符串
    比如var s = 0x41424344
    0x41 对应 ‘A’
    0x42 对应 ‘B’
    0x43 对应 ‘C’
    0x44 对应 ‘D’
    如果直接 var str = “” + s,只是将number字符串化 : str = “1094861636”
    但是,我想要的是 str = “ABCD”
function Int32CodetoStr(x){
		var str= ""
		var t = x
		var arr = []
		var i = 0
		while(t>0){
			arr[i++] = t&0xff
			t = t >>8
		}
		i--;
		while(i>=0){
		 str = str + String.fromCharCode(arr[i--])
		}
		
		return str
	}

减少拼接次数和fromCharCode调用,提高效率:

function Int32CodetoStr(x){
		var t = x
		var arr = []
		var i = 0
		while(t>0){
			arr[i++] = t&0xff
			t = t >>8
		}
		switch(i){
			case 1: return String.fromCharCode(arr[0])
			case 2: return String.fromCharCode(arr[1],arr[0])
			case 3: return String.fromCharCode(arr[2],arr[1],arr[0])
			case 4: return String.fromCharCode(arr[3],arr[2],arr[1],arr[0])
		}
		return ""
	}
  • number to(N进制)字符串
var n = 15

//16进制
var str_16 = n.toString(16)//"f"

//10进制
var str_10 = n.toString(10)//"15"

//2进制
var str_2  = n.toString(2)//"1111"

*(N进制)字符串 to number

var s = "11"

//对于字符串"11",如果按照16进制理解0x11 => 17
var num_16 = parseInt(s,16)//17

//对于字符串"11",如果按照10进制理解11 => 11
var num_10 = parseInt(s,10)//11

//对于字符串"11",如果按照2进制理解0b11 =>3
var num_2 = parseInt(s,10)//3

文章来源:https://blog.csdn.net/jiangliuhuan123/article/details/135125651
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。