Sivvie Lim
Sivvie Lim

Reputation: 1286

How to convert from string to 16-bit unsigned integer in python?

I'm currently working on some encoding and decoding of the string in python. I was supposed to convert some code from C# to python, however I encountered some problem as below:

So now I have a string that looks like this: 21-20-89-00-67-00-45-78 The code was supposed to eliminates the - in between the numbers, and packed 2 integers into 1 group, then convert them into bytes. In C#, it was done like this:

var value = "21-20-89-00-67-00-45-78";
var valueNoDash = value.Replace("-", null);
for (var i = 0; i < DataSizeInByte; i++)
{
    //convert every 2 digits into 1 byte
    Data[i] = Convert.ToByte(valueNoDash.Substring(i * 2, 2), 16);
}

The above code represents Step 1: Remove - from the string, Step 2: using Substring method to divide them into 2 digits in 1 group, Step 3: use Convert.ToByte with base 16 to convert them into 16-bit unsigned integer. The results in Data is

33
32
137
0
103
0
69
120

So far I have no problem with this C# code, however when I try to do the same in python, I could not get to the same result as the C# code. My python code are as below:

from textwrap import wrap
import struct

values = "21-20-89-00-67-00-45-78"
values_no_dash = a.replace('-', '')
values_grouped = wrap(b, 2)
values_list = []

for value in values_grouped:
    values_list.append(struct.pack('i', int(value)))

In python, it gives me list of bytes in hex value, which is as below:

b'\x15\x00\x00\x00'
b'\x14\x00\x00\x00'
b'Y\x00\x00\x00'
b'\x00\x00\x00\x00'
b'C\x00\x00\x00'
b'\x00\x00\x00\x00'
b'-\x00\x00\x00'
b'N\x00\x00\x00'

This is in bytes object, however when I converted this object into Decimal, it gives me the exact same value as the original string: 21, 20, 89, 0, 67, 0, 45, 78.

Which means I did not convert successfully into 16-bit unsigned integer right? How can I do this in python? I've tried using str.encode() but the result still different. How can I achieve what C# had done in python?

Thanks and appreciates if anyone can help!

Upvotes: 1

Views: 5590

Answers (1)

Michele Bastione
Michele Bastione

Reputation: 363

I think this is the solution you're looking for:

values = "21-20-89-00-67-00-45-78"
values_no_dash_grouped = values.split('-') #deletes dashes and groups numbers simultaneously 
for value in values_no_dash_grouped:
    print(int(value, 16)) #converts number in base 16 to base 10 and prints it

Hope it helps!

Upvotes: 2

Related Questions