0

I've array of char [HEX]. I've no idea how to convert them to integer. Anyone guide me an idea?

My Coding:

char Hex[] = {'01', '0D'};

int a = (int(Hex[0]) >> 8)+ int(Hex[1]);
int b = (Hex[0] << 8) | Hex[1];

cout << "a: " << a << " b: " << b;

Output:

a: 68 b: 12612

I suppose output should be:

269
taocp
  • 23,276
  • 10
  • 49
  • 62
  • This question might be helpful: http://stackoverflow.com/questions/1070497/c-convert-hex-string-to-signed-integer – Kirby Apr 11 '13 at 03:25
  • 1
    hex is short for hexidecimal or base 16. So your code should multiply by 16 or shift by 4 if you want hard to read code. – brian beuning Apr 11 '13 at 03:36
  • `char Hex[] = {'01', '0D'};` you need to find out what that means before trying to do more. It's not what you think it is. It's the same as `char Hex[] = {'1', 'D'};` – Drew Dormann Apr 11 '13 at 03:47
  • Just in case it's not clear try `char Hex[] = {0x01, 0x0D};` and you'll get the output you want. – john Apr 11 '13 at 06:24

2 Answers2

1

What you're completely missing is the ASCII conversion.

'f' is a character, with value 0x6f. Obviously that's not the same as 0x0f.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
0

your question is very hard to figure out. I think this is what you want. Here's how to convert 15 to F and F to 15. I hope this is what you're asking

#include<iostream>
#include<sstream>

int main(){
  // decimal to hex
  std::cout << std::hex << 15 << std::endl;

  // hex to decimal
  int mydecimal;
  std::istringstream("f") >> std::hex >> mydecimal;
  std::cout << std::dec << mydecimal << std::endl;

  // hex to decimal method 2
  std::cout << std::dec << 0xf << std::endl;
}
Wilmer E. Henao
  • 4,094
  • 2
  • 31
  • 39