【问题标题】:Java - Parser Library to parse a decimal to byte in x-bitsJava - 解析器库将十进制解析为 x 位中的字节
【发布时间】:2012-07-05 20:28:11
【问题描述】:

解析器有问题。

问题是我得到一个整数,例如“8”,我需要将其转换为 8 位无符号字节。 稍后我将收到一个整数“56”,需要使用相同的方法对其进行转换,但当我收到“-53”(例如)时,我会说这是通信和发送中的错误。

例如,

number = 538; //or 63492873 or 8 or 17826312631 or -231 or whatever
try{
  byte response[] = Parse8BitUnsigned(number);
}catch(Idkexcepcion ex){
  System.out.println("the number is a signed one");
  byte response[] = Parse8BitSigned(number);
}

注意:Parse8BitSigned() 和 Parse8BitSigned() 尚未实现。任何号码我都需要这种方法

【问题讨论】:

  • 您的问题是什么,java.lang.Integer.valueOf("8") 是答案吗?
  • 我的问题是,int 到 8bit 字节数组,比如 byte response[] = Parse8Bit(8);
  • 您想要的只是解析 positive 值,而不是 unsignedunsignedsigned 是一种表示形式。例如有符号字节范围从 [-128;127]

标签: java parsing converter 8-bit


【解决方案1】:

你可以使用ByteBuffer做你想做的事:

String number="8";
int num = Integer.valueOf(number);
if(num < 0 ) //ERROR
// Return 8 in a 4 bytes array
byte[] bytes = ByteBuffer.allocate(4).putInt(num).array();

【讨论】:

    猜你喜欢
    • 2015-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    • 2015-11-23
    • 2015-08-02
    • 1970-01-01
    相关资源
    最近更新 更多