i have array : byte set[6] = { 0xa8,0x12,0x84,0x03,0x00,0x00, }
, need insert value : "" int value = 1200; ""
....on last 4 bytes. practically convert int hex , write inside array... possible ?
i have bitconverter::getbytes
function, that's not enough.
thank you,
to answer original quesion: sure can. sizeof(int) == 4
, sizeof(byte) == 1
.
but i'm not sure mean "converting int hex". if want hex string representation, you'll better off using 1 of standard methods of doing it. example, on last line use std::hex print numbers hex.
here solution you've been asking , little more (live example: http://codepad.org/rsmzngul):
#include <iostream> using namespace std; int main() { const int value = 1200; unsigned char set[] = { 0xa8,0x12,0x84,0x03,0x00,0x00 }; (const unsigned char* c = set; c != set + sizeof(set); ++c) { cout << static_cast<int>(*c) << endl; } cout << endl << "putting value array:" << endl; *reinterpret_cast<int*>(&set[2]) = value; (const unsigned char* c = set; c != set + sizeof(set); ++c) { cout << static_cast<int>(*c) << endl; } cout << endl << "printing int's bytes 1 one: " << endl; (int bytenumber = 0; bytenumber != sizeof(int); ++bytenumber) { const unsigned char onebyte = reinterpret_cast<const unsigned char*>(&value)[bytenumber]; cout << static_cast<int>(onebyte) << endl; } cout << endl << "printing value hex: " << hex << value << std::endl; }
upd: comments question: 1. if need getting separate digits out of number in separate bytes, it's different story. 2. little vs big endianness matters well, did not account in answer.
Comments
Post a Comment