How does this denary to binary program work? I am finding it hard to comprehend what is happening behind the code.
Can someone explain the lines 6 onwards?
Number = int(input("Hello. \n\nPlease enter a number to convert: "))
if Number < 0:
print ("Can't be less than 0")
else:
Remainder = 0
String = ""
while Number > 0:
Remainder = Number % 2
Number = Number // 2
String = str(Remainder) + String
print (String)
The idea is to separate out the last part of the binary number, stick it in a buffer, and then remove it from "Number". The method is general and can be used for other bases as well.
Start by looking at it as a dec -> dec "conversion" to understand the principle.
Let's say you have the number 174 (base10). If you want to parse out each individual piece (read as "digit") of it you can calculate the number modulo the base (10), then do an integer division to "remove" that digit from the number. I.e. 174%10 and 174//10 => (Number) 17|4 (Reminder). Next iteration you have 17 from the division and when you perform the same procedure, it'll split it up into 1|7. On the next iteration you'll get 0|1, and after that "Number" will be 0 (which is the exit condition for the loop (while Number > 0)).
In each iteration of the loop you take the remainder (which will be a single digit for the specific base you use (it's a basic property of how bases work)), convert it to a string and concatenate it with the string you had from previous iterations (note the order in the code!), and you'll get the converted number once you've divided your way down to zero.
As mentioned before, this works for any base; you can use base 16 to convert to hex (though you'll need to do some translations for digits above 9), octal (base 8), etc.
Python code for converting denary into binary
denary= int(input('Denary: '))
binary= [0,0,0,0]
while denary>0:
for n,i in enumerate(binary):
if denary//(2**(3-n))>=1:
binary[n]= 1
denary -= 2**(3-n)
print(denary)
print (binary)
Related
R = [cos(pi/3) sin(pi/3); -sin(pi/3) cos(pi/3)]
[i,j]=round([1 1] * R)
returns
i =
-0 1
error: element number 2 undefined in return list
While I want i=0 and j=1
Is there a way to work around that? Or just Octave being stupid?
Octave is not being stupid; it's just that you expect the syntax [a,b] = [c,d] to result in 'destructuring', but that's not how octave/matlab works. Instead, you are assigning a 'single' output (a matrix) to two variables. Since you are not generating multiple outputs, there is no output to assign to the second variable you specify (i.e. j) so this is ignored.
Long story short, if you're after a 'destructuring' effect, you can convert your matrix to a cell, and then perform cell expansion to generate two outputs:
[i,j] = num2cell( round( [1 1] * R ) ){:}
Or, obviously, you can collect the output into a single object, and then assign to i, and j separately via that object:
[IJ] = round( [1 1] * R ) )
i = IJ(1)
j = IJ(2)
but presumably that's what you're trying to avoid.
Explanation:
The reason [a,b] = bla bla doesn't work, is because syntactically speaking, the [a,b] here isn't a normal matrix; it represents a list of variables you expect to assign return values to. If you have a function or operation that returns multiple outputs, then each output will be assigned to each of those variables in turn.
However, if you only pass a single output, and you specified multiple return variables, Octave will assign that single output to the first return variable, and ignore the rest. And since a matrix is a single object, it assigns this to i, and ignores j.
Converting the whole thing to a cell allows you to then index it via {:}, which returns all cells as a comma separated list (this can be used to pass multiple arguments into functions, for instance). You can see this if you just index without capturing - this results in 'two' answers, printed one after another:
num2cell( round( [1 1] * R ) ){:}
% ans = 0
% ans = 1
Note that many functions in matlab/octave behave differently, based on whether you call them with 1 or 2 output arguments. In other words, think of the number of output arguments with which you call a function to be part of its signature! E.g., have a look at the ind2sub function:
[r] = ind2sub([3, 3], [2,8]) % returns 1D indices
% r = 2 8
[r, ~] = ind2sub([3, 3], [2,8]) % returns 2D indices
% r = 2 2
If destructuring worked the way you assumed on normal matrices, it would be impossible to know if one is attempting to call a function in "two-outputs" mode, or simply trying to call it in "one-output" mode and then destructure the output.
I've been searching and searching and my Google-fu has failed me. I'm trying to convert an encoded number from base-32 to decimal using either expressions or a macro, but I'm not finding anything. I know Excel has the "Decimal" function, I've been hoping that I could stumble onto something similar.
I'm reluctant to use VBA as I don't want to spend time re-learning the language right now and I'm worried that my organization will flag it as potentially dangerous (which could kill my attempts at making any databases).
With an input of "16O9E55"
I expect a result of 1300543653.
I should clarify that this is "base32hex" according to Wikipedia. It's 0-9, A-V. It's only 7 characters of base-32 that needs to convert to 10 digits of decimal. My use case is decoding a barcode into the data I need.
I doubt this can be accomplished without VBA. Consider code adapted from https://www.excelbanter.com/excel-worksheet-functions/150198-formulat-convert-base-32-decimal.html
Public Function Base32ToDec(Num As String) As Variant
Static Digits As String
Dim i As Integer
Dim myIndex As Integer
Dim myStr As String
Digits = "0123456789ABCDEFGHIJKLMNOPQRSTUV"
For i = Len(Num) To 1 Step -1
myStr = Mid(Num, i, 1)
myIndex = InStr(Digits, myStr) - 1
Base32ToDec = Base32ToDec + myIndex * 32 ^ (Len(Num) - i)
Next i
End Function
According to Wikipedia, Base32 uses a 32-character set comprising the twenty-six upper-case letters A–Z, and the digits 2–7. The variant base32hex starts with 0 - 9 and uses the letters A to V.
If only numbers with a limited range have been encoded, you can decode them easily with VBA, otherwise you would have to return an array of bytes and process it further.
You write, that you have up to 10 decimal digits. The question is, what the maximum number is. The Long type can store numbers up to 2,147,483,647. This are ten digits; however, with 10 digits you could store a number as big as 9,999,999,999.
Therefore, the following function returns the number as Double. If you know that your number will never exceed 2,147,483,647, then you can exchange the Double type by Long for the sum variable and the function return type.
Public Function DecodeBase32hex(ByVal encoded As String) As Double
Dim ch As String
Dim sum As Double
Dim d As Long, i As Long
For i = 1 To Len(encoded)
ch = Mid$(encoded, i, 1)
If ch >= "A" And ch <= "Z" Then
d = Asc(ch) - Asc("A") + 10
ElseIf ch >= "0" And ch <= "9" Then
d = Asc(ch) - Asc("0")
Else
Exit For 'E.g. padding charachters
End If
sum = 32 * sum + d
Next i
DecodeBase32hex = sum
End Function
Test in Access' immediate window:
?DecodeBase32hex("16O9E55")
1300543653
I am writing a program. there is a binary floating number like this format : XX.XXX. for example,binary floating number 01.101 convert to decimal number is 1.625. I tried it for a long time, but couldn't work it out.
I use [4:0]num to store the number. num[4:3] is the integer part, num[2:0] is the floating part. the integer part is easy, when num[2:0]=3'b101, it means that the binary floating part is 0.101, and convert to decimal number is 0.625. so how can I convert the sequence"101", get a sequence "625"?
The quickest way is probably just to use a LUT (lookup table). Since the fractional portion is only 3 bits, that leaves you with only 8 possibilities. And you could use an 12bit value where each nibble is a digit that could be sent to a display etc.
reg result[11:0] // each nibble represents a digit
always #(*) begin
case (num[2:0])
3'b000 : result = 12'h000;
3'b001 : result = 12'h125;
3'b010 : result = 12'h250;
3'b011 : result = 12'h375;
3'b100 : result = 12'h500;
3'b101 : result = 12'h625;
3'b110 : result = 12'h750;
default : result = 12'h875;
endcase
end
In VHDL, If X'1 => "0001", X'3 => "0011". i.e, 1 hex digit represents 4 binary values, how do i represent only 2 binary values in hex given that i have only a specific bit range in memory. In this case 2. For instance, the space left in memory can only take 2 bits. I know i can still use the initial representation and mask out either the two msb's or lsb's but is there another way ?
You can do this if you are using VHDL-2008:
2X"2" = "0010"
Further examples from web:
unsigned notation (default):
7UX"F" = "0001111" -- extend
7UX"0F" = "0001111" -- reduce
signed noataion:
7SX"F" = "1111111" -- extend
7SX"CF" = "1001111" -- reduce
In the code below I try to find prime numbers. My problem is that, I am not sure how to use print inside a function.
Is it correct? I get an answer but it both says 6 is not a prime number and it also gives "None". How can I get rid of this "None"? Also, is it okay to use return just like this?
#Prime number
def prime(num):
for i in range (2,num):
if num%i == 0:
print num, "is not a prime number."
return
else:
print num, "is a prime number."
return
print prime(6)
First of all you have print statements in your code already so just calling prime will result in stuff being printed to the screen. When you have a bare return your function will return None. That means that when you do:
print prime(6)
prime(6) will return None which makes this equivalent to:
print None
Then you have a major logic error in your code because you do not check every possible divisor due to returning too early. For example if you have the number be 9, this is not a prime number. However your function will print that it is a prime because on the first run through the for loop i will be 2 which means 9%2 is false so the else branch gets taken and it prints out that the number is prime. The function then returns at that point without checking the rest of the numbers. If you run this code you will see what happens: http://ideone.com/zxdez2
The design issue here is that you really should keep IO separate from the rest of the functionality. Say you wanted to reuse prime somewhere else later on you can't do this without also having that code print out to the screen. This might not be what you want at that later date but it's hard to do something with that. Instead it is much cleaner to return a boolean that represents if the number was prime or not then print out based on that returned value:
def prime(num):
for i in range (2,num):
if num%i == 0:
return False
return True
x = 6
if prime(x):
print x, "is not a prime number."
else:
print x, "is a prime number."