Reputation: 533
I have a csv file which contains data in two columns. The data is in decimal format.
I am trying to convert the data into hexadecimal format, then concatenate it.
I am able to convert and concatenate when data in column2 is non-zero.
For example: Column1 = 52281 and Column2 = 49152, then i am able to get CC39C000. (hex(52281) = CC39 and hex(49152) = C000).
However, if data in Column2 is zero:-
Column1 = 52281 and Column2 = 0, then i get CC390 instead of CC390000.
Following is my code snippet:-
file=open( inputFile, 'r')
reader = csv.reader(file)
for line in reader:
col1,col2=int(line[0]),int(line[1])
newstr = '{:x}'.format(col1)+'{:x}'.format(col2)
When the data in column2 is 0, i am expecting to get 0000.
How can i modify my code to achieve this??
Upvotes: 0
Views: 168
Reputation: 6129
If you have
a=52281
b=0
You can convert yo hex and calculate the longest string to fill with zeros
hex_a = hex(a)[2:] # [2:] removes the trailing 0x you might want to use [3:] if you have negative numbers
hex_b = hex(b)[2:]
longest=max(len(hex_a), len(hex_b))
Then you can fill with 0 with the zfill
method:
print(hex_a.zfill(longest) + hex_b.zfill(longest))
If you only need 4 characters you can do zfill(4)
If I am trying to adapt your code, which is hard to test because I do not have access to the file,
file=open( inputFile, 'r')
reader = csv.reader(file)
for line in reader:
col1,col2=int(line[0]),int(line[1])
hex_col1 = hex(col1)[2:] if col1>=0 else hex(col1)[3:]
hex_col2 = hex(col2)[2:] if col2>=0 else hex(col2)[3:]
longest = max(len(hex_col1), len(hex_col2))
newstr = hex_col1.zfill(longest) + hex_col2.zfill(longest)
Upvotes: 1