41 lines
1.1 KiB
Rust
41 lines
1.1 KiB
Rust
use crate::error::{CliError, Result};
|
||
|
||
pub fn encode_gnacs(data: &str) -> Result<String> {
|
||
// 简化实现:将字符串转换为48位二进制
|
||
let bytes = data.as_bytes();
|
||
if bytes.len() > 6 {
|
||
return Err(CliError::Encoding("数据过长,最多6字节".to_string()));
|
||
}
|
||
|
||
let mut result = String::new();
|
||
for byte in bytes {
|
||
result.push_str(&format!("{:08b}", byte));
|
||
}
|
||
|
||
// 补齐到48位
|
||
while result.len() < 48 {
|
||
result.push('0');
|
||
}
|
||
|
||
Ok(result)
|
||
}
|
||
|
||
pub fn decode_gnacs(gnacs: &str) -> Result<String> {
|
||
if gnacs.len() != 48 {
|
||
return Err(CliError::Encoding("GNACS编码必须是48位二进制".to_string()));
|
||
}
|
||
|
||
let mut bytes = Vec::new();
|
||
for i in (0..48).step_by(8) {
|
||
let byte_str = &gnacs[i..i+8];
|
||
let byte = u8::from_str_radix(byte_str, 2)
|
||
.map_err(|_| CliError::Encoding("无效的二进制字符串".to_string()))?;
|
||
if byte != 0 {
|
||
bytes.push(byte);
|
||
}
|
||
}
|
||
|
||
String::from_utf8(bytes)
|
||
.map_err(|_| CliError::Encoding("无效的UTF-8字符串".to_string()))
|
||
}
|