public final byte[] getParam(String commandName,String memLocation,String dataId){
byte[] result = new byte[9];
result[0] = START_FRAME.getBytes()[0];
result[1] = START_FRAME.getBytes()[0];
result[2] = Integer.toHexString(commandMap.get(commandName)).getBytes()[0];
result[3] = Integer.toHexString(dataIdMap.get(dataId)).getBytes()[0];
result[4] = Integer.toHexString(locationMap.get(memLocation)).getBytes()[0];
result[5] = Integer.toHexString(commandMap.get(commandName) + dataIdMap.get(dataId) + locationMap.get(memLocation)).getBytes()[0];
result[6] = END_FRAME.getBytes()[0];
result[7] = END_FRAME.getBytes()[0];
result[8] = END_OF_LINE.getBytes()[0];
开发者_JAVA技巧 //Check sum -> {{d10d}}
return result;
}
how can i reduce the result[5] addition of values to a function call...
can i pass like this ?
public static final byte[] createCheckSum(byte[] paramsToBeAdded){
byte[] result = paramsToBeAdded;
............
........... etc
return result[0] + result[2];
}
Correct answer:
private String createCheckSum(byte[] byteHolder,int startIndex,int endIndex){
byte[] byteToCompute = byteHolder;
int sum = 0;
for(int i=startIndex; i<=endIndex; i++){
sum += Integer.valueOf(byteToCompute[i]);
}
return Integer.toHexString(sum);
}
Looks like your using some class member variables. In that case, a function would make the code a bit more readable (choose a good name that shows what the method is doing):
private String computeSomething(String commandName,String memLocation,String dataId) {
int commandValue = commandMap.get(commandName);
int dataValue = dataIdMap.get(dataId);
byte memValue = locationMap.get(memLocation)).getBytes()[0];
return Integer.toHexString(commandValue + dataValue + memValue);
}
call it like this:
result[5] = computeSomething(commandName, memLocation, dataId);
(and replace the name computeSomething
for the readabilty effect)
精彩评论