How to print 4-byte integer byte by byte in C++

2 Answers

0 votes
#include <iostream>

int main() {
    unsigned int n = 1150336788;
    unsigned char* p = reinterpret_cast<unsigned char*>(&n);
    
    std::cout << "Integer hex value: 0x" << std::hex << n << std::endl;
    
    std::cout << "Byte by byte: " << static_cast<unsigned int>(*p) << " "
              << static_cast<unsigned int>(*(p + 1)) << " "
              << static_cast<unsigned int>(*(p + 2)) << " "
              << static_cast<unsigned int>(*(p + 3)) << std::endl;
}


/*
run:

Integer hex value: 0x4490bf14
Byte by byte: 14 bf 90 44

*/

 



answered Jul 28, 2024 by avibootz
0 votes
#include <iostream>
 
int main() {
    unsigned int n = 1150336788;
    unsigned char* p = (unsigned char*)&n;
     
    std::cout << "Integer hex value: " << std::hex << n << "\n";
    std::cout << "Integer value: " << std::dec << n << "\n";
 
    std::cout << "Byte by byte: " << (unsigned int)(*p) << " "
              << (unsigned int)(*(p + 1)) << " "
              << (unsigned int)(*(p + 2)) << " "
              << (unsigned int)(*(p + 3)) << "\n";
}
 
// 14 hex = 20 dec
// BF hex = 191 dec
// 90 hex = 144 dec
// 44 hex = 68 dec
 
  
  
/*
run:
  
Integer hex value: 4490bf14
Integer value: 1150336788
Byte by byte: 20 191 144 68
  
*/

 



answered Jul 28, 2024 by avibootz
edited Jul 28, 2024 by avibootz

Related questions

1 answer 47 views
1 answer 73 views
1 answer 184 views
1 answer 87 views
1 answer 102 views
...