将一个c#方法改成java方法,不要工具自动转换的代码,谢谢,
我要的答案是懂C#和JAVA,且输入输出经过测试是一致的publicstringGetCheckString(stringcmd){stringresult="";UIn...
我要的答案是懂C#和JAVA,且输入输出经过测试是一致的
public string GetCheckString(string cmd)
{
string result = "";
UInt16 sum = 0;
int len = cmd.Length;
foreach (UInt16 nItemCharValue in cmd)
{
sum += nItemCharValue;
}
sum = (UInt16)((UInt16)(~sum) + 1);
string szCheckString = sum.ToString("X").PadLeft(4, '0');
result = cmd + szCheckString + '\r';
return result;
} 展开
public string GetCheckString(string cmd)
{
string result = "";
UInt16 sum = 0;
int len = cmd.Length;
foreach (UInt16 nItemCharValue in cmd)
{
sum += nItemCharValue;
}
sum = (UInt16)((UInt16)(~sum) + 1);
string szCheckString = sum.ToString("X").PadLeft(4, '0');
result = cmd + szCheckString + '\r';
return result;
} 展开
展开全部
import java.util.*;
// 以下为java version
public class Test {
public static void main(String[] args) {
System.out.println(GetCheckString("cmd"));
}
/**
* @param cmd 入力参数
* @return
*/
public static String GetCheckString(String cmd) {
String result = "";
int sum = 0;
int len = cmd.length();
for (int index = 0; index < len; index++) {
char nItemCharValue = cmd.charAt(index);
sum += nItemCharValue;
}
sum = (int) ((~sum) + 1);
// String szCheckString = sum.toString("X").PadLeft(4, '0');
System.out.println(Integer.toHexString(sum));
String szCheckString = Test.padLeft((Integer.toHexString(sum) + ""), 4);
result = cmd + szCheckString + '\r';
return result;
}
/**
* 模拟C#的PadLeft()
* @param s 入力字符串
* @param length 指定长度
* @return
*/
public static String padLeft(String s, int length) {
byte[] bs = new byte[length];
byte[] ss = s.getBytes();
Arrays.fill(bs, (byte) (48 & 0xff));
if (length < ss.length)
return s;
System.arraycopy(ss, 0, bs, length - ss.length, ss.length);
return new String(bs);
}
}
更多追问追答
追问
同样以“cmd"为参数,C#输出结果为cmdFECC,而你写的方法输出结果为cmdfffffecc
大侠,继续,谢谢。结果对了,马上结题。
追答
/**
* @param cmd 传入参数
* @return
*/
public static String GetCheckString(String cmd) {
String result = "";
int sum = 0;
int len = cmd.length();
for (int index = 0; index < len; index++) {
char nItemCharValue = cmd.charAt(index);
sum += nItemCharValue;
sum = sum & 0x0FFFF;
}
// 做一次转换,将有符号的int转换为无符号的int16
sum = (( ~(sum & 0x0FFFF)) + 1)& 0x0FFFF;
// String szCheckString = sum.toString("X").PadLeft(4, '0');
System.out.println(Integer.toHexString(sum));
String szCheckString = Test.padLeft((Integer.toHexString(sum) + ""), 4);
result = cmd + szCheckString + '\r';
return result;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |