Java-将字符串(4个字符)转换为int并返回的乐趣 [英] Java - fun converting a string (4 chars) to int and back
本文介绍了Java-将字符串(4个字符)转换为int并返回的乐趣的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请不要问为什么,但是我必须将一个字符串(最多4个字符)存储在一个整数值(即4个字节)中.
Please don't ask why but I have to store a string (max 4 char) in an integer value (so 4 bytes).
首先,我写了这个,它起作用了:
First I wrote this and it works:
String value = "AAA";
int sum = IntStream.range(0, value.length())
.limit(4)
.map(i -> value.charAt(i) << (i * 8))
.sum();
System.out.println(sum);
我无法想出可行的解决方案.
I was unable to think a functional solution for the way back.
StringBuffer out = new StringBuffer();
while (sum > 0) {
int ch = sum & 0xff;
sum >>= 8;
out.append((char) ch);
}
有任何想法以实用的方式写回"AAA"的方法吗?
Any idea to write the way back (to "AAA") in a functional way?
推荐答案
与您的非常相似,但可能会有所帮助
That's pretty similar to yours, but maybe will be helpful
String str = IntStream.iterate(sum, s -> s > 0, s -> s >> 8)
.mapToObj(s -> String.valueOf((char)(s & 0xff)))
.collect(Collectors.joining());
这篇关于Java-将字符串(4个字符)转换为int并返回的乐趣的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文