[英]numeric to writeBytes / Java
我需要從數據庫中的表中獲取一個數字,然后將其作為ChannelBuffer放入寬度為4個字節的字段中。
該數字可以是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);
這將轉換為大端字節(二進制):
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;
}
不知道您想要在bufcmd中使用哪種編碼等,我將大膽猜測“無論使用哪種String都可以”
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()調用。
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)) );
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.