473,549 Members | 2,366 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

decimal to binary

How to convert a decimal to binary ?

thx,

Manuel
Jul 18 '05 #1
9 30099
>>>>> "manuel" == manuel <ma************ ******@tin.it> writes:

manuel> How to convert a decimal to binary ? thx,

1. Divide the "desired" base (in this case base 2) INTO the
number you are trying to convert.

2. Write the quotient (the answer) with a remainder like you did
in elementary school.

3. Repeat this division process using the whole number from the
previous quotient (the number in front of the remainder).

4. Continue repeating this division until the number in front of
the remainder is only zero.

5. The answer is the remainders read from the bottom up.

Is this what you meant :-)? Or do you want to convert an integer to a
binary string in python? If the latter, see the struct module
http://www.python.org/doc/current/li...le-struct.html

John Hunter

Jul 18 '05 #2
manuel wrote:

How to convert a decimal to binary ?


No builtin function, but you could likely find lots of previous
questions like this, and answers.

If you don't feel like searching, can you post an example of
what you want in and what you want out? Some people asking
this kind of question are confused about representations
of numbers and how data is really stored in computers, and
they don't really want what they thing they want.

A quick Google groups search with "convert decimal binary"
reveals answers that would probably work for you.

-Peter
Jul 18 '05 #3
manuel wrote:
How to convert a decimal to binary ?


def foo(i):
b = ''
while i > 0:
j = i & 1
b = str(j) + b
i >>= 1
return b

Maybe this is inefficient, but...

-Manish

--
Manish Jethani (manish.j at gmx.net)
phone (work) +91-80-51073488

Jul 18 '05 #4
On Friday 25 July 2003 05:21 am, manuel wrote:
How to convert a decimal to binary ?

thx,

Manuel


We probably need more information than that to answer your question.
For instance statement

x = 123

converts the decimal number represented by the decimal digits 123 into
binary form and stores it in variable x. Of course you have no access
to the binary digits as

print x

converts back to decimal to print "123"

So what is it you really want?

Gary Herron

Jul 18 '05 #5
> We probably need more information than that to answer your question.

I'm writing a script for Blender to make a true displacement
feature. This is a sample:
http://www.kino3d.com/forum/files/test4.jpg

and this is the discussion:
http://www.elysiun.com/forum/viewtop...postorder=asc&
start=0
Please, excuse me for my poor english, it's very
hard for me to explain a development question,
because I'm italian, and I've little time to study
other language...Real ly I prefer study 3D and python. :-P
The main problem with newsgroup it that
after send the message I can't modify it... :-(

This is the first time that I try to handle
binary file.

I read a tga file, and store all bytes in a list:

---------------------------------------
#LETTURA DEL FILE TGA
listByte = []
try:
f = open(filename,' rb')
except IOError,(errno, strerror):
msgstring = "I/O error(%s): %s" % (errno, strerror); Draw()
return
fileReaded = f.read();
msgstring = "Parsing tga..."; Draw()
for i in range(len(fileR eaded)):
listByte.append (ord(fileReaded[i]))
f.close()
------------------------------------------

I use ord() to convert the value of byte in
integer, if I don't make this, I've the ASCII
symbol...

But, for listByte[17], I must read the sequence
of 0 and 1, because I must know the 4° and 5° bit:
this bits specify the image origin.

How I can read the 4° and 5° bit from listByte[17]?

Thanks,

Manuel Bastioni


Jul 18 '05 #6
manuel wrote:
This is the first time that I try to handle
binary file.

I read a tga file, and store all bytes in a list:

---------------------------------------
#LETTURA DEL FILE TGA
listByte = []
try:
f = open(filename,' rb')
except IOError,(errno, strerror):
msgstring = "I/O error(%s): %s" % (errno, strerror); Draw()
return
fileReaded = f.read();
msgstring = "Parsing tga..."; Draw()
for i in range(len(fileR eaded)):
listByte.append (ord(fileReaded[i]))
f.close()
------------------------------------------

I use ord() to convert the value of byte in
integer, if I don't make this, I've the ASCII
symbol...
You CAN store the byte as it is, in a string. So, for example,
you can store
'a(*@'
instead of
[97, 40, 42, 64]
But it depends on your requirements.
But, for listByte[17], I must read the sequence
of 0 and 1, because I must know the 4° and 5° bit:
this bits specify the image origin.


This function returns the binary representation as a string:

def foo(i):
b = ''
while i > 0:
j = i & 1
b = str(j) + b
i >>= 1
return b

bin = foo(listByte[17])
bin[-4] # 4th (3rd) bit
bin[-5] # 5th (4th) bit

You have to check for IndexError, or check the length of the string.

BUT! But you don't need to do this in order to get the value of
the 4th (3rd) bit. Just do this:

if listByte[17] & (1 << 3):
<bit is set>
else:
<bit is not set>

For the 5th (4th) bit, change '<< 3' to '<< 4'; and so on.

-Manish

--
Manish Jethani (manish.j at gmx.net)
phone (work) +91-80-51073488

Jul 18 '05 #7
On Fri, 25 Jul 2003 18:52:00 GMT, "manuel"
<ma************ ******@tin.it> wrote:
I use ord() to convert the value of byte in
integer, if I don't make this, I've the ASCII
symbol...

But, for listByte[17], I must read the sequence
of 0 and 1, because I must know the 4° and 5° bit:
this bits specify the image origin.

How I can read the 4° and 5° bit from listByte[17]?

You can use this function to generate a list of digits (least
significant first!) from any integer, with the default being the 8
binary digits of one byte (and no checking for anything):

def digitlist(value , numdigits=8, base=2):
val = value
digits = [0 for i in range(numdigits )]
for i in range(numdigits ):
val, digits[i] = divmod(val, base)
return digits
digitlist(234) # binary 11101010 [0, 1, 0, 1, 0, 1, 1, 1] digitlist(39) # binary 00100111

[1, 1, 1, 0, 0, 1, 0, 0]

Now you can easily access the 4th and 5th elements (which are probably
reversed if you needed the 4th and 5th bit most significant first)...

Hope this helps,
Christopher

--
Christopher
Jul 18 '05 #8
> if listByte[17] & (1 << 3):
Thanks!

But I don't understand completely the meaning of
& (1 << 3)

Can you suggest me a page in python on line manual,
or a tutorial?


Jul 18 '05 #9
manuel wrote:
if listByte[17] & (1 << 3):
Thanks!

But I don't understand completely the meaning of
& (1 << 3)


(1 << 3) will left-shift 1 by 3 bits

00000000 00000000 00000000 00000001

giving you 8

00000000 00000000 00000000 00001000

Then you AND your number (25, for example) with 8

00000000 00000000 00000000 00011001
00000000 00000000 00000000 00001000
-----------------------------------
00000000 00000000 00000000 00001000

if you get a non-zero value, then the bit is set.

If your number is 23

00000000 00000000 00000000 00010111
00000000 00000000 00000000 00001000
-----------------------------------
00000000 00000000 00000000 00000000

then the result of the AND is 0, and that means the bit is not set.
Can you suggest me a page in python on line manual,
or a tutorial?


See the section on bit-wise operations in the Python Reference
Manual.

-Manish

--
Manish Jethani (manish.j at gmx.net)
phone (work) +91-80-51073488

Jul 18 '05 #10

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

Similar topics

21
4498
by: Batista, Facundo | last post by:
Here I send it. Suggestions and all kinds of recomendations are more than welcomed. If it all goes ok, it'll be a PEP when I finish writing/modifying the code. Thank you. .. Facundo
17
6115
by: John Bentley | last post by:
John Bentley: INTRO The phrase "decimal number" within a programming context is ambiguous. It could refer to the decimal datatype or the related but separate concept of a generic decimal number. "Decimal Number" sometimes serves to distinguish Base 10 numbers, eg "15", from Base 2 numbers, Eg "1111". At other times "Decimal Number" serves to...
5
1973
by: Michael A. Covington | last post by:
Microsoft's documentation is a bit unclear, but is Decimal in fact a radix-100 (base-100) arithmetic data type (in which each byte ranges only from 0 to 99)? It should be straightforward to dump some Decimal values onto a binary file (or into a stream that writes into an array of bytes) and examine them.
687
23002
by: cody | last post by:
no this is no trollposting and please don't get it wrong but iam very curious why people still use C instead of other languages especially C++. i heard people say C++ is slower than C but i can't believe that. in pieces of the application where speed really matters you can still use "normal" functions or even static methods which is...
2
3454
by: Steve Summit | last post by:
-----BEGIN PGP SIGNED MESSAGE----- It's often explained that the reason for some of the imprecision in C's definition is so that C can be implemented on different kinds of machines -- say, those with 2's complement, 1's complement, or sign-magnitude arithmetic. But the followup remark is sometimes also made that the choice of arithmetic...
1
1640
by: lmh86 | last post by:
Should the following algorithm produce the binary equivalent of an inputed decimal value? ---------- cout << "Decimal value: "; cin >> Decimal; Binary = 0; Remainder = Decimal; for(Power = 4; Power = -1; Power--) { Remainder = Decimal - (pow(2,Power));
28
5836
by: FAQ server | last post by:
----------------------------------------------------------------------- FAQ Topic - How do I convert a Number into a String with exactly 2 decimal places? ----------------------------------------------------------------------- When formatting money for example, to format 6.57634 to 6.58, 6.5 to 6.50, and 6 to 6.00? Rounding of x.xx5 is...
2
4489
by: Tukeind | last post by:
Hello, I am receiving the following error: error C2065: 'to_binary' : undeclared identifier while running the code below. If anyone can help I'll appreciate it? Thank you, Tukeind
3
8836
by: zgfareed | last post by:
My program converts decimal numbers from to binary and hexadecimal. I am having trouble with my output which is supposed to be in a certain format. Binary needs to be in the format of XXXX XXXX for numbers 0 to 255. What am doing wrong or not doing with my output? Source code: // code #include <iostream>
0
28047
Frinavale
by: Frinavale | last post by:
Convert a Hex number into a decimal number and a decimal number to Hex number This is a very simple script that converts decimal numbers into hex values and hex values into decimal numbers. The example following this one demonstrates how to convert decimal numbers into binary values. A hex number is a string that contains numbers between...
0
7471
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7740
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7503
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7830
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6071
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5387
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3496
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1082
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
784
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.