473,385 Members | 1,838 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

int('\x23') != 0x23 (a.k.a convert char to integer of its byte representation)

Hi,

I am looking for the best way to convert a string of length 1 (= 1
character as string) to integer that has the same value as numeric
representation of that character. Background: I am writing functions
abstracting endianness, e.g. converting a string of length 4 to the
appropriate integer value (e.g. '\x01\x00\x00\x00' = 2**24 for big
endian memory, 2**0 for little endian memory). For this, I need to
know the numeric value of each byte and sum them according to
endianness.

I thought that something like int('\x01') might work, provided the
argument is string of length 1, but that throws an error:
>>int('\x12')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: invalid literal for int():

The code I want to write looks like this:

mem = '\x11\x22\x33\x44'
factor = 1
sum = 0
for byte in mem:
sum += int(byte) * factor
factor *= 2**8

Could you please tell me how to achieve what I want in Python? (it
would be straightforward in C)

Thanks for any suggestions,
Boris Dušek

Sep 15 '07 #1
3 2862
On Sat, 15 Sep 2007 11:55:28 +0000, Boris Dušek wrote:
I am looking for the best way to convert a string of length 1 (= 1
character as string) to integer that has the same value as numeric
representation of that character. Background: I am writing functions
abstracting endianness, e.g. converting a string of length 4 to the
appropriate integer value (e.g. '\x01\x00\x00\x00' = 2**24 for big
endian memory, 2**0 for little endian memory). For this, I need to
know the numeric value of each byte and sum them according to
endianness.
So you are looking for the `struct` module in the standard library instead
of doing this yourself. :-)

If you insist on doing it yourself take a look at the built-in `ord()`
function.

Ciao,
Marc 'BlackJack' Rintsch
Sep 15 '07 #2
On Sep 15, 1:59 pm, Marc 'BlackJack' Rintsch <bj_...@gmx.netwrote:
So you are looking for the `struct` module in the standard library instead
of doing this yourself. :-)

If you insist on doing it yourself take a look at the built-in `ord()`
function.
Thanks Marc,

both things are exactly what I was looking for (I am a bit ashamed
that I did not find the built-in ord :-)

Boris

Sep 15 '07 #3
On Sep 15, 9:55 pm, Boris Dušek <boris.du...@gmail.comwrote:
Hi,

I am looking for the best way to convert a string of length 1 (= 1
character as string) to integer that has the same value as numeric
representation of that character. Background: I am writing functions
abstracting endianness, e.g. converting a string of length 4 to the
appropriate integer value (e.g. '\x01\x00\x00\x00' = 2**24 for big
endian memory, 2**0 for little endian memory). For this, I need to
know the numeric value of each byte and sum them according to
endianness.

I thought that something like int('\x01') might work, provided the
argument is string of length 1, but that throws an error:
>int('\x12')

Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: invalid literal for int():

The code I want to write looks like this:

mem = '\x11\x22\x33\x44'
factor = 1
sum = 0
for byte in mem:
sum += int(byte) * factor
factor *= 2**8

Could you please tell me how to achieve what I want in Python? (it
would be straightforward in C)
'BlackJack' has already sent you looking for the docs for ord() and
the struct module but a few other clues seem necessary:

1. Don't "think that something like int() might work", read the docs.

2. "factor *= 2 **8"?? Python compiles to bytecode; don't make it work
any harder than it has to. "factor" is quite unnecessary. That loop
needs exactly 1 statement:
sum = (sum << 8) + ord(byte)

3. Don't use "sum" as a variable name; it will shadow the sum() built-
in function.

4. Read through the docs for *all* the built-in
functions -- all kinds of interesting and useful gadgets to be found
there.

5. In a dark corner there lives a strange beast called the array
module:
>>import array
array.array('I', '\x01\x00\x00\x00')[0]
1L
>>array.array('I', '\x00\x00\x00\x01')[0]
16777216L
>>2**24
16777216
>>>
HTH,
John

Sep 15 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Philipp H. Mohr | last post by:
Hello, I am trying to xor the byte representation of every char in a string with its predecessor. But I don't know how to convert a char into its byte representation. This is to calculate the...
17
by: cpptutor2000 | last post by:
Could some C guru help me please? A byte is an unsigned char in C. How do I convert from a C string to a corresponding byte array. Any help would be greatly appreciated.
11
by: QQ | last post by:
I know a char is 2 bytes, the conversion is like byte byte_array = new byte; //Allocate double mem as that of char then for each char do byte = (byte) char & 0xff byte = (byte)( char >> 8 &...
7
by: Sagaert Johan | last post by:
if i have a variable decllared as : char mychararray = new char; and i have some method that needs an byte how do i cast or convert this ? (byte) mychararray does not work
2
by: Marius Cabas | last post by:
How can I convert a String or a char to byte?
7
by: MilanB | last post by:
Hello How to convert char to int? Thanks
3
by: David | last post by:
Hi, how to convert a char array(byte) to a string variable? byte buffer; string strTest; /*the blow codes all get type of 'buffer': System.Byte! strTest = buffer.ToString() strTest =...
6
by: John A Grandy | last post by:
How to copy an char to a byte , where the char holds unicode characters ?
27
by: fdu.xiaojf | last post by:
Hi, String formatting can be used to converting an integer to its octal or hexadecimal form: '307' 'c7' But, can string formatting be used to convert an integer to its binary form ?
12
by: Peter | last post by:
Trying to convert string to byte array. the following code returns byte array of {107, 62, 194, 139, 64} how can I convert this string to a byte array of {107, 62, 139, 65} ...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.