Click here to Skip to main content
15,891,431 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
good evening,
I am trying to develop an application allows me to create an automation system.
I have a little problem about an order; the operator will input a decimal number eg 100000 which is in hex 0x186A0 so just divide it into 3 parts 0x01 0x86 0xA0
can you help me to advance in my project ?
You will find attached the program code:
C++
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <iostream>
#include <string>        
#include <sstream> 
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
	uint16_t res1 = 0xFFFFFF;
	int D = 0;
	uint8_t tab[3];
	printf("donner valeur decimal: ", D);
	cin >> D;
	std::stringstream ss;
	ss << std::hex << D;
	std::string res(ss.str());
	std::cout << res;

	res1 = (uint16_t)res.c_str();
	
	tab[0] = res1 & 0xFF;
	printf("\n val 1: %x", tab[0]);
	tab[1] = (res1 & 0xFF, res1 >> 8) ;
	printf("\n val 2: %x", tab[1]);
	tab[2] = (res1 & 0xFF, res1 >> 16);
	printf("\n val 3: %x", tab[2]);

	return 0;
}
Posted
Updated 23-Feb-15 10:17am
v2

1 solution

You may just use a union:
C++
#include <iostream>
#include <stdint.h>

union IntByte
{
  uint32_t i;
  uint8_t b[4];
};

int main()
{
  IntByte ib;

  std::cout << "donner valeur decimal: ";
  std::cin >> ib.i;

  for (int i=0; i<3; ++i)
  {
    std::cout << "val[" << i << "] = " << std::hex << (uint32_t) ib.b[2-i] << std::endl;
  }
}
 
Share this answer
 
v2
Comments
Member 11441147 23-Feb-15 16:42pm    
thank you ! it work :D
CPallini 24-Feb-15 3:36am    
You are welcome.
Sergey Alexandrovich Kryukov 23-Feb-15 18:25pm    
Sure, a 5.
—SA
CPallini 24-Feb-15 3:36am    
Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900