472,798 Members | 1,192 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,798 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 2807
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: erikbower65 | last post by:
Using CodiumAI's pr-agent is simple and powerful. Follow these steps: 1. Install CodiumAI CLI: Ensure Node.js is installed, then run 'npm install -g codiumai' in the terminal. 2. Connect to...
0
linyimin
by: linyimin | last post by:
Spring Startup Analyzer generates an interactive Spring application startup report that lets you understand what contributes to the application startup time and helps to optimize it. Support for...
0
by: kcodez | last post by:
As a H5 game development enthusiast, I recently wrote a very interesting little game - Toy Claw ((http://claw.kjeek.com/))。Here I will summarize and share the development experience here, and hope it...
0
by: Taofi | last post by:
I try to insert a new record but the error message says the number of query names and destination fields are not the same This are my field names ID, Budgeted, Actual, Status and Differences ...
14
DJRhino1175
by: DJRhino1175 | last post by:
When I run this code I get an error, its Run-time error# 424 Object required...This is my first attempt at doing something like this. I test the entire code and it worked until I added this - If...
0
by: Rina0 | last post by:
I am looking for a Python code to find the longest common subsequence of two strings. I found this blog post that describes the length of longest common subsequence problem and provides a solution in...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
0
by: lllomh | last post by:
How does React native implement an English player?
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...

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.