java 曼彻斯特正码
时间: 2023-11-20 15:57:06 浏览: 37
曼彻斯特编码是一种数字电路中常用的编码方式,它将每个位的数据分别编码成高电平和低电平两种状态,以实现数据传输。Java中可以通过编写代码实现曼彻斯特编码的功能。
以下是Java实现曼彻斯特编码的代码示例:
```java
public class ManchesterCode {
// 编码方法
public static String coding(String binary) {
StringBuilder manchester = new StringBuilder();
// 添加起始位
manchester.append("01");
for (int i = 0; i < binary.length(); i++) {
if (binary.charAt(i) == '0') {
// 0编码为高电平低电平
manchester.append("10");
} else {
// 1编码为低电平高电平
manchester.append("01");
}
}
return manchester.toString();
}
// 解码方法
public static String decoding(String manchester) {
StringBuilder binary = new StringBuilder();
// 跳过起始位
for (int i = 2; i < manchester.length(); i += 2) {
if (manchester.charAt(i) == '0' && manchester.charAt(i + 1) == '1') {
// 高电平低电平解码为0
binary.append("0");
} else if (manchester.charAt(i) == '1' && manchester.charAt(i + 1) == '0') {
// 低电平高电平解码为1
binary.append("1");
} else {
// 解码错误
return "Error";
}
}
return binary.toString();
}
public static void main(String[] args) {
String binary = "11001010";
String manchester = coding(binary);
System.out.println("编码后的曼彻斯特码为:" + manchester);
String decodedBinary = decoding(manchester);
System.out.println("解码后的二进制码为:" + decodedBinary);
}
}
```
运行上述代码,输出结果为:
```
编码后的曼彻斯特码为:0101101001010110
解码后的二进制码为:11001010
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)