-2

I have a string like this:

std::string s="840D8E88B0AC";

and an array:

char MAC[6];

I want to produce this:

MAC={0x84,0x0D,0x8E,0x88,0xB0,0xAC};

I try with sscanf() but I can't make it.

sscanf(s.c_str(), "%02X%02X%02X%02X%02X%02X", MAC[0], MAC[1], MAC[2], MAC[3], MAC[4], MAC[5]);
nima
  • 5
  • 2

1 Answers1

1

It should be (other errors notwithstanding)

sscanf(s.c_str(), "%02X%02X%02X%02X%02X%02X", &MAC[0], &MAC[1], &MAC[2], 
    &MAC[3], &MAC[4], &MAC[5]);

sscanf (and variants) require pointers in order to change the variables that are being read into.

Surprised your compiler didn't warn you about that error.

john
  • 85,011
  • 4
  • 57
  • 81
  • I've already tried this, but it does not work.The output is: – nima Jan 02 '19 at 14:02
  • 1
    @nima: This looks good to me. What doesn't work about it? – Bathsheba Jan 02 '19 at 14:03
  • The output is: {-124,13,-114,-120,-80,-84} I need exactly {0x84,0x0D,0x8E,0x88,0xB0,0xAC} or even {84,0D,8E,88,B0,AC} – nima Jan 02 '19 at 14:10
  • @nima -124 and 0x84 are the same, 13 and 0x0D are the same, just different base and different signedness. You're going to have to be clearer about exactly what you want because it's not making much sense at the moment – john Jan 02 '19 at 14:16
  • I check the value by watch in visual studio. I need to pass MAC to a function. – nima Jan 02 '19 at 14:19
  • @nima Well Visual Studio is just printing the same numbers in a different way. The code is correct. The number thirteen is 13 in decimal, and 0x0D in hexadecimal, it's all the same thing. – john Jan 02 '19 at 14:21
  • @nima Internally C++ just has numbers, it doesn't have hexadecimal numbers or decimal numbers. Those are just differences in the way numbers are printed. The same number can be printed in several different ways – john Jan 02 '19 at 14:25
  • In fact, your explanation worked! I pass the variable and function work correctly. thank you Bathsheba and john. – nima Jan 02 '19 at 14:27