字符串转字节以及字节转字符串
HTML运行网址:HTML/CSS/JS 在线工具 | 菜鸟工具 (jyshare.com)
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>字符串与字节数组转换</title>
<style>
body {
font-family: Arial, sans-serif;
}
.container {
display: flex;
justify-content: space-around;
align-items: center;
height: 100vh;
}
textarea {
width: 300px;
height: 200px;
padding: 10px;
margin-bottom: 10px;
}
button {
padding: 10px 20px;
margin: 0 10px;
}
</style>
</head>
<body>
<div class="container">
<div>
<textarea id="inputStr" placeholder="请输入字符串"></textarea>
</div>
<div>
<button id="strToBytes">转为流格式</button>
<button id="bytesToStr">转为字符串</button>
</div>
<div>
<textarea id="outputBytes" placeholder="字节数组输出"></textarea>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function () {
const inputStr = document.getElementById('inputStr');
const outputBytes = document.getElementById('outputBytes');
const strToBytes = document.getElementById('strToBytes');
const bytesToStr = document.getElementById('bytesToStr');
strToBytes.addEventListener('click', function () {
const str = inputStr.value;
const encoder = new TextEncoder();
const byteArray = Array.from(encoder.encode(str));
outputBytes.value = byteArray.join(', ');
});
bytesToStr.addEventListener('click', function () {
const bytesStr = outputBytes.value;
const byteArray = bytesStr.split(', ').map(Number);
const decoder = new TextDecoder();
const str = decoder.decode(new Uint8Array(byteArray));
inputStr.value = str;
});
});
</script>
</body>
</html>