Converting input from non-integer bit rates into something workable

  • A+
Category:Languages

I have a program whose input has changed. It originally worked when using integers and the integers had units like: "kbps", "Mbps", "Gbps". An example:

10kbps 20Mbps 20Gbps 

I used "if/then" to convert all strings to bps:

if "kbps" in bandwidth:     bw=bandwidth.replace('kbps', '000') elif "Mbps" in bandwidth:     bw=bandwidth.replace('Mbps', '000000') elif "Gbps" in bandwidth:     bw=bandwidth.replace('Gbps', '000000000') else:     bw='0' 

I'd print "bw" as an integer "int(bw)", and it worked fine. Now, the input has changed. Here are samples of actual inputs:

3.838Mbps 100kbps 126.533kbps 5.23Mbps 100Mbps 1.7065Gbps 20Gbps 

The numbers are not integers. Not only can I not print because it is not an integer, the unit conversion doesn't work with decimals. For example, 3.838Mbps becomes 3.838000000.

Can someone suggest an efficient way to work with these inputs? I can't find the right balance of splitting, regexp matching, etc. and am wondering if there are some methods I don't know about.

 


You can cast value before kbps, Mbps or Gbps to float and multiply it by 1000, 1000,000 and so on. That will work for either case.

For Example:

if "kbps" in bandwidth:     bw = bandwidth.replace('kbps', '')     bw = str(float(bw) * 1000) elif "Mbps" in bandwidth:     bw = bandwidth.replace('Mbps', '')     bw = str(float(bw) * 1000* 1000) elif "Gbps" in bandwidth:     bw = bandwidth.replace('Gbps', '')     bw = str(float(bw) * 1000 * 1000 * 1000) else:     bw='0' 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: