Advertisement
Guest User

Untitled

a guest
Oct 19th, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.94 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. int hexToDec(string hex)
  6. {
  7. int dec=0;
  8. int n=hex.size();
  9. for(int i=2;i<n;i++) //ignoruje miejsce 0 i 1 bo to "0x"
  10. {
  11. dec*=16;
  12. if(hex[i]<='9') dec+=hex[i]-'0';
  13. else dec+=hex[i]-'a'+10;
  14. }
  15. return dec;
  16. }
  17.  
  18. string decToHex(string dec)
  19. {
  20. int iDec=0;
  21. int n=dec.size();
  22. for(int i=0;i<n;i++) //zamiana stringa dec na inta iDec
  23. {
  24. iDec*=10;
  25. iDec+=dec[i]-'0';
  26. }
  27.  
  28. string hex="";
  29. while(iDec>0) //zamiana inta iDec na stringa (hex) reprezentującego jego zapis szesnastkowy
  30. {
  31. int digit = iDec%16;
  32. char c; //cyfra szesnastkowa odpowiadajaca intowi digit
  33. if(digit<10) c=digit+'0';
  34. else c=digit+'a'-10;
  35. hex = c+hex;
  36. iDec/=16;
  37. }
  38. hex = "0x"+hex;
  39. return hex;
  40. }
  41.  
  42. int main()
  43. {
  44. string a;
  45. cin>>a;
  46. while(a!="-1")
  47. {
  48. if(a[1]=='x')
  49. {
  50. cout<<hexToDec(a)<<endl;
  51. }
  52. else
  53. {
  54. cout<<decToHex(a)<<endl;
  55. }
  56. cin>>a;
  57. }
  58. return 0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement