我需要从数据库中的表中获取一个数字,并在一个宽度为4个字节的字段中添加一个ChannelBuffer。
数字可以是1到9999,例如。 237并且在ChannelBuffer中我需要填充4个字节。
ChannelBuffer bufcmd = ChannelBuffers.directBuffer(4);
bufcmd.writeByte(0x00); // 1º digit of 4 bytes
bufcmd.writeByte(0x00); // 2º digit of 4 bytes
bufcmd.writeByte(0x00); // 3º digit of 4 bytes
bufcmd.writeByte(0x01); // 4º digit of 4 bytes
如何直接用237值填写?
整个代码是:
String strcmd = "dyd#"; //from database
ChannelBuffer bufcmd = ChannelBuffers.directBuffer(100);
bufcmd.writeByte(0x78);
bufcmd.writeByte(0x78);
bufcmd.writeByte((5 + strcmd.length()));
bufcmd.writeByte(0x80);
bufcmd.writeByte((4 + strcmd.length()));
// TODO: convert 1 to 9999 to HEX
// (id of command from database eg: 3)
// but filling 4 bytes
bufcmd.writeByte(0x00);
bufcmd.writeByte(0x00);
bufcmd.writeByte(0x00);
bufcmd.writeByte(0x03);
bufcmd.writeBytes(ChannelBuffers.copiedBuffer(strcmd, CharsetUtil.US_ASCII));
bufcmd.writeShort(buf.readUnsignedShort());
bufcmd.writeShort(Crc.crc16Ccitt(bufcmd.toByteBuffer(2, 4)));
bufcmd.writeByte(0x0D);
bufcmd.writeByte(0x0A);
channel.write(bufcmd);
答案 0 :(得分:0)
这将转换为big endian,binary:
int theNumber = 237;
byte[] buf = new byte[4];
for( int i = 0; i < 4; i++ ){
buf[3 - i] = (byte)(theNumber & 0xFF);
theNumber = theNumber >> 8;
}
请注意,java.io.DataOutputStream和类似的类具有方法writeInt(int v)和其他类型的类似方法,这简化了您认为具有考虑因素的任务。
下面的代码转换为十进制ASCII,首先是最高有效数字,前导零:
int theNumber = 237;
byte[] buf = new byte[4];
for( int i = 0; i < 4; i++ ){
buf[3 - i] = (byte)(theNumber % 10 + 0x30);
theNumber = theNumber / 10;
}
答案 1 :(得分:-1)
如果不知道你想要在你的bufcmd中使用哪种编码等,我就会疯狂地猜测“无论字符串使用的是什么都没关系”
int theNumber = 237; // The value
String theString = Integer.toString(theNumber); //The string representation of the value
for(int i=0; i<4;i++)
{
bufcmd.writeByte( theString.charAt(i) );
}
补充:一个完整的实现,它考虑了字符串长度并添加了零填充,并且还将字符转换为整数,如果你不需要这个,删除包裹字符的Character.getNumericValue()调用.. < / p>
int theNumber = 237; // The value
String theString = Integer.toString(theNumber); //The string representation of the value
int len = theString.length(); //Bytes in the string
int requiredLen = 4; // 3 = 0003, 42 = 0042
int padding = requiredLen-len; //How many 0 we need to send first
while( padding-- > 0 )
{
bufcmd.writeByte( 0 );
}
for(int i=0; i<len;i++)
{
bufcmd.writeByte( Character.getNumericValue(theString.charAt(i)) );
}
您还可以使用Math.pow计算位置的值,而不是将其转换为字符串。
这是一个证明该方法有效的测试。 http://www.compileonline.com/compile_java_online.php
public class HelloWorld{
public static void main(String []args){
System.out.println("Hello World");
int theNumber = 237; // The value
String theString = Integer.toString(theNumber); //The string representation of the value
int len = theString.length(); //Bytes in the string
int requiredLen = 4; // 3 = 0003, 42 = 0042
int padding = requiredLen-len; //How many 0 we need to send first
while( padding-- > 0 )
{
System.out.println( 0 );
}
for(int i=0; i<len;i++)
{
System.out.println( Character.getNumericValue(theString.charAt(i)) );
}
}
}