将US-ASCII编码的字节转换为整数并返回 [英] Converting US-ASCII encoded byte to integer and back

查看:318
本文介绍了将US-ASCII编码的字节转换为整数并返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大小为2,3或4的字节数组。我需要将其转换为正确的整数值。我还需要反向执行此操作,即字节数组为2,3或4个字符的整数。

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.

例如,原始十六进制字节为:54和49。解码后的字符串US-ASCII值为61.所以整数答案需要为61。

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?

如果我做 new String(lne,US-ASCII ),其中 lne 是我的字节数组,我得到正确的61.但是当这样做时((int) lne [0]<< 8)| ((int)lne [1]& 0xFF),我得到了完全错误的答案。

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.

这可能是一个愚蠢的错误或者我完全不理解Java中的数字表示方案和编码/解码的想法。

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?

推荐答案

您需要两个转换步骤。首先,将ascii字节转换为字符串。这就是 new String(lne,us-ascii)为你做的。 然后,将数字的字符串表示形式转换为实际数字。为此您使用类似 Integer.parseInt(theString)的东西 - 记得处理NumberFormatException。

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.

这篇关于将US-ASCII编码的字节转换为整数并返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆