0

I am trying to parse an array of ascii characters which form a number (float, int...) Sometimes array length is 1, 2, 3....8... I am looking for a way to get the whole array (with just one complete value each time) and return the number to add it to a json.

I am using python 3. Is there a fixed function to do that? I haven't found anything on the internet yet.

I was thinking in something like this:

return arrayBytes[0]<<8 | arrayBytes[1]

But I get values like 574 in a % value so it has to be wrong and just would work with 2 ascii array length.

Here you have an example of the input:

4 value: 0x32 0x38 0x2e 0x36
2 value 0x34 0x39 
3 value 0x30 0x2e 0x34
12
  • 1
    Show us a sample of the input. Commented Aug 12, 2014 at 14:34
  • 4 value: 0x32 0x38 0x2e 0x36, 2 value 0x34 0x39, 3 value 0x30 0x2e 0x34 Commented Aug 12, 2014 at 14:36
  • 0x32 0x38 0x2e 0x36 is 28.6 as ASCII; are you sure these are not just numbers already? Commented Aug 12, 2014 at 14:38
  • How do you know how many bytes to read? Commented Aug 12, 2014 at 14:40
  • They are numbers. I need to rejoin to get the 28.6 you printed Commented Aug 12, 2014 at 14:40

2 Answers 2

1

You appear to have ASCII representations of numbers:

>>> '\x32\x38\x2e\x36'
'28.6'
>>> '\x34\x39'
'49'
>>> '\x30\x2e\x34'
'0.4'

Calling float() on these to turn them into Python float objects is enough:

>>> float('\x32\x38\x2e\x36')
28.6
>>> float('\x34\x39')
49.0
>>> float('\x30\x2e\x34')
0.4

If your input is integers, then they represent ASCII codepoints. In Python 3, use bytes() to quickly turn those back to text:

>>> bytes([50, 57, 46, 57])
b'29.9'
>>> bytes([50, 57, 46, 57]).decode('ascii')
'29.9'
>>> float(bytes([50, 57, 46, 57]))
29.9

In Python 2, use bytearray() instead:

>>> bytearray([50, 57, 46, 57])
bytearray(b'29.9')
>>> str(bytearray([50, 57, 46, 57]))
'29.9'
>>> bytearray([50, 57, 46, 57]).decode('ascii')
u'29.9'
>>> float(bytearray([50, 57, 46, 57]))
29.9

Either way you can go from list of integers to bytes, text or a floating point value with ease.

Sign up to request clarification or add additional context in comments.

Comments

0

You won't be able to use bitwise operations because those only work with small python integers. Instead you will need to multiply by the equivalent power of two.

mult = 1 << 8
answer = 0
for number in asciiBytes:
    answer *= mult
    answer += number

If you are just storing a string representation of the number, and not storing the number as the bitwise pieces separated, then call float(str) to turn the string into a number.

For example float('423.3') == 423.3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.