Converting US-ASCII encoded byte to integer and back

亡梦爱人 提交于 2019-12-12 14:14:30

问题


I have a byte array that can be of size 2,3 or 4. I need to convert this to the correct integer value. I also need to do this in reverse, i.e an 2,3 or 4 character integer to a byte array.

e.g., raw hex bytes are : 54 and 49. The decoded string US-ASCII value is 61. So the integer answer needs to be 61.

I have read all the conversion questions on stackoverflow etc that I could find, but they all give the completely wrong answer, I dont know whether it could be the encoding?

If I do new String(lne,"US-ASCII"), where lne is my byte array, I get the correct 61. But when doing this ((int)lne[0] << 8) | ((int)lne[1] & 0xFF), I get the complete wrong answer.

This may be a silly mistake or I completely don't understand the number representation schemes in Java and the encoding/decoding idea.

Any help would be appreciated.

NOTE: I know I can just parse the String to integer, but I would like to know if there is a way to use fast operations like shifting and binary arithmetic instead?


回答1:


You need two conversion steps. First, convert your ascii bytes to a string. That's what new String(lne,"us-ascii") does for you. Then, convert the string representation of the number to an actual number. For that you use something like Integer.parseInt(theString) -- remember to handle NumberFormatException.




回答2:


Here's a thought on how to use fast operations like byte shifting and decimal arithmetic to speed this up. Assuming you have the current code:

byte[] token;  // bytes representing a bunch of ascii numbers
int n = Integer.parseInt(new String(token));  // current approach

Then you could instead replace that last line and do the following (assuming no negative numbers, no foreign langauge characters, etc.):

int n = 0;
for (byte b : token)
  n = 10*n + (b-'0');

Out of interest, this resulted in roughly a 28% speedup for me on a massive data set. I think this is due to not having to allocate new String objects and then trash them after each parseInt call.




回答3:


As you say, new String(lne,"US-ASCII") will give you the correct string. To convert your String to an integer, use int myInt = Integer.parseInt(new String(lne,"US-ASCII"));



来源:https://stackoverflow.com/questions/6974335/converting-us-ascii-encoded-byte-to-integer-and-back

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!