freedev :
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);
}
Any idea to write the way back (to "AAA") in a functional way?
Michel_T. :
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());