简体   繁体   English

数字写入字节/ Java

[英]numeric to writeBytes / Java

I need to get a numeric from a table in database and put it a ChannelBuffer in a field with 4 bytes of width. 我需要从数据库中的表中获取一个数字,然后将其作为ChannelBuffer放入宽度为4个字节的字段中。

The number can be 1 to 9999 eg. 该数字可以是1至9999,例如。 237 and in ChannelBuffer I need to fill the 4 bytes. 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

How can I fill this directly with 237 value? 如何直接用237值填充?

The entire code is: 整个代码是:

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);

This converts to 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;
   }

Note that java.io.DataOutputStream and similar classes have method writeInt(int v) and similar methods for other types, which simplifies tasks like the one you appear to have considerabls. 请注意,java.io.DataOutputStream和类似的类具有方法writeInt(int v)和其他类型的类似方法,从而简化了您似乎考虑过的任务。

The code below converts to decimal ASCII, most significant digit first, leading zeros: 下面的代码将转换为十进制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;
   }

Without knowing which encoding etc you want in your bufcmd, I'm going to take a wild guess that "whatever String is using is okay" 不知道您想要在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) );
}

Added: A full implementation which takes into account string lengths and adds zero padding and also translates the character into an integer, if you do not need this, remove the Character.getNumericValue() call that wraps around the character.. 补充:一个完整​​的实现,该实现考虑了字符串长度并添加了零填充,还将字符转换为整数,如果不需要,请删除包裹在字符周围的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)) );
}

You can also calculate the value of a position instead of translating it to a string using Math.pow. 您也可以计算位置值,而不是使用Math.pow将其转换为字符串。

Here is a test to prove that the method works. 这是一个测试证明该方法有效的测试。 http://www.compileonline.com/compile_java_online.php 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.

相关问题 Java套接字编程写入readline - Java socket programming writebytes to readline 使用writeBytes的Java客户端套接字 - Java client socket using writeBytes Java-多次使用writeBytes之后程序崩溃 - Java - Program crashing after multiple uses of writeBytes 为什么我们在Java中将InputBytes写入OutputStream并从InputStream读取readLine? - Why we writeBytes into a OutputStream and readLine out of a InputStream in java? 为什么Java writeBytes方法在第一个TCP数据包中仅发送一个字节,而write方法却不发送? - Why does Java writeBytes method send only one byte in first TCP packet and write method does not? io.netty.ByteBuf writeBytes(java.nio.ByteBuffer src) API说明 - io.netty.ByteBuf writeBytes(java.nio.ByteBuffer src) APIclarification JAVA-从GPS接收器检索NMEA帧-有关RandomAccessFile WriteBytes方法的更多详细信息 - JAVA - Retrieve NMEA frame from a GPS Receptor -More details about RandomAccessFile WriteBytes method 为什么 Java 11 在 ByteArrayOutputStream 类中添加了 writeBytes​(byte[] b) 方法,而 write​(byte[] b) 方法也一样? - Why did Java 11 add writeBytes​(byte[] b) method to the ByteArrayOutputStream class while the write​(byte[] b) method did the same? writeBytes对服务器/客户端程序不起作用 - writeBytes not working for Server/Client Program 正则表达式:数字范围 java - Regex: Numeric Range java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM