alright, I'm new to this community and I have been reading the beginners posts, and I am still having trouble. I need to design a function for a class. It needs to convert decimal numbers to base 16. So for example if the input is 705083, then the function should return AC23B. I have been trying to do this and am having some trouble. I am going to keep trying but I would appreciate any help I can get. Thanks a lot

Recommended Answers

All 4 Replies

alright, I'm new to this community and I have been reading the beginners posts, and I am still having trouble. I need to design a function for a class. It needs to convert decimal numbers to base 16. So for example if the input is 705083, then the function should return AC23B. I have been trying to do this and am having some trouble. I am going to keep trying but I would appreciate any help I can get. Thanks a lot

Number is a number, a coulpe of bytes in memory. It's more about representation....
Try this:

def foo (x):
	try:
		y = int (x)
	except ValueError:
		print 'Not a valid number'
	return '%X' % y
	
	
print foo(705083)

- Micko

Like Micko said, it is in the representation ...

# two different ways to represent integer 705083 as a hexadecimal number
# 0x is the official prefix for a hexnumber
# the results appear different, but both are of type string and change back to base 10 properly
# pick the one you prefer

# using the hex() function
hex1 = hex(705083)
print hex1, type(hex1), int(hex1,16)  # result = 0xac23b <type 'str'> 705083

# using the format operator %
hex2 = "%X" % 705083
print hex2, type(hex2), int(hex2,16)  # result = AC23B <type 'str'> 705083

Just a note, I timed the two options with timeit and the hex() is two times faster than the format operator. So it might depend on how often you call your function. The old LOOKS over SPEED decision.

Vegaseat, Micko gave the correct answer to CutCrusader's question. Your answer with the zero x in front does not.

I'm still working on it, but I really appreciate your guy's help. After I posted I read your "homework policy" and felt a little bad for asking for help. But I appreciate you guys taking the time.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.