Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent Scala for the following Python statement?

Tags:

python

scala

What is the equivalent Scala for the following Python statement? It looks like it's using an unsigned long or something (which Scala doesn't have).

size = pack('!L', len(someString))
like image 744
Bruce Ferguson Avatar asked Dec 30 '25 19:12

Bruce Ferguson


1 Answers

According to the python docs the pack method does the following:

Return a string containing the values v1, v2, ... packed according to the given format. The arguments must match the values required by the format exactly.

The ! means Big Endian, the L means Unsigned Long.

You're right, Scala does not have unsigned numerics. But this is not important, because it only means, that the passed in value must be in the range of an unsigned long.

See this output:

>>> pack("!L", 2442442424)
'\x91\x94\xb6\xb8'
>>> pack("!l", 2442442424)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
struct.error: 'l' format requires -2147483648 <= number <= 2147483647

I don't think there is an equivalent method in scala's or java's stdlib, but it shouldn't be hard to write one. You only have to convert your number to big endian and then convert it to a byte array.

like image 124
drexin Avatar answered Jan 02 '26 09:01

drexin