我想将一个 Char 更改为具有相同位结构的 Short。 都是 16 位
我知道short是2s补码,如果它们是1s补码我可以使用
if a < 0 {return (short) math.abs a + 2 ^ 15;} else {return (short) a;} //right?
如何对 2s 补负数执行此操作?
我只是希望能够像操作 Integer 一样操作 Char 的内部结构。
如果答案只是添加一个,我会变得情绪化:)
最佳答案
简单的解决方案就是这样做
char ch = ...
short s = (short) ch;
char ch2 = (char) s;
// ch == ch2
也许您认为它必须比实际情况更复杂;)
I simply want to be able to manipulate the innards of a Char in the same way as I can a Integer.
在这种情况下,您甚至不需要 short
,您需要一个更简单的 int
。
例如
// sum all the chars of a string
String s = "Hello World";
int sum = 0;
for(char ch: s.toCharArray())
sum += ch;
If the answer is just add one I am going to become emotional
不,甚至比这个还要少。 :j
顺便说一句,你可以做
char ch = 'A';
int i = ch + 0;
int j = ch;
关于java - 将 Char 更改为具有相同位结构的 Short。 (2的补码问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14650889/