printing selected bytes of an int variable

This is a discussion on printing selected bytes of an int variable within the C++ Programming forums, part of the General Programming Boards category; Hey, I want to print only the last byte if an unsigned int variable. It's Big-Endian, so only the last ...

  1. #1
    Registered User
    Join Date
    May 2005
    Location
    Toronto, Canada
    Posts
    257

    printing selected bytes of an int variable

    Hey,

    I want to print only the last byte if an unsigned int variable. It's Big-Endian, so only the last byte will have the value if it's under 255. What's the clever way to do it?

  2. #2
    Registered User mitakeet's Avatar
    Join Date
    Jun 2005
    Location
    Maryland, USA
    Posts
    212
    Make a char * pointer to it and print whatever byte you want:

    char *ptr = (char *)&intValue;

    cout << ptr[3];

    Free code: http://sol-biotech.com/code/.

    It is not that old programmers are any smarter or code better, it is just that they have made the same stupid mistake so many times that it is second nature to fix it.
    --Me, I just made it up

    The reasonable man adapts himself to the world; the unreasonable one persists in trying to adapt the world to himself. Therefore, all progress depends on the unreasonable man.
    --George Bernard Shaw

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,588
    hmm... would doing a (num & 255) work in this case?
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  4. #4
    Registered User
    Join Date
    May 2005
    Location
    Toronto, Canada
    Posts
    257
    > num & 255

    Would just clear out the rest of the bytes, but if I were to print if in binary it would still print the 0's.

    I'm working on the pointer.

  5. #5
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,588
    but if I were to print if in binary it would still print the 0's.
    How are you printing in binary?
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  6. #6
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Code:
    #include <iostream>
    #include <climits>
    
    int main()
    {
       unsigned long value  = 0x12345678UL;
       unsigned char hibyte = value >> ((sizeof value - 1) * CHAR_BIT);
       std::cout << std::hex << static_cast<unsigned int>(hibyte) << std::endl;
       return 0;
    }
    
    /* my output
    12
    */
    [edit]
    so only the last byte will have the value if it's under 255
    Methinks I may have gone the wrong direction.
    Code:
    #include <iostream>
    #include <climits>
    
    int main()
    {
       unsigned int  value  = 0x12345678;
       unsigned char lobyte = value;
       std::cout << std::hex << static_cast<unsigned int>(lobyte) << std::endl;
       return 0;
    }
    
    /* my output
    78
    */
    Look ma, no endianness!
    Last edited by Dave_Sinkula; 07-13-2005 at 09:16 AM.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  7. #7
    Registered User
    Join Date
    May 2005
    Location
    Toronto, Canada
    Posts
    257
    yep, the pointer works, but apperantly it wanted to print the 1st byte instead of the last, as I expected. Correct me if I'm wrong:
    if I use say int x = vectorX.size(); The actual size will be stored in the first byte of x. I originally thought that it would be in the last byte since the most sig. bit is in the 1st possition.
    what's going with the whole big-endian and little endian thing? If I use windows and MS Visual C++ compiler, whouldn't they both be big-andian and put the number in the last byte of x if it's under 255?

  8. #8
    Registered User
    Join Date
    May 2005
    Location
    Toronto, Canada
    Posts
    257
    > Printing in binary.

    I meant print it to a binary file.

    But I also may be super confused......

  9. #9
    Magically delicious LuckY's Avatar
    Join Date
    Oct 2001
    Posts
    856
    Use a union:
    Code:
    #include <iostream>
    using namespace std;
    
    
    int main() {
      union {
        int numeric;
        unsigned char bytes[sizeof(int)];    
      } u;
      
      u.numeric = 0xFF;
      cout << (int)u.bytes[0] << endl;// prints 255
      
      return 0;
    }

  10. #10
    Registered User mitakeet's Avatar
    Join Date
    Jun 2005
    Location
    Maryland, USA
    Posts
    212
    Intel is little endian, so everything is 'backwards'.

    Free code: http://sol-biotech.com/code/.

    It is not that old programmers are any smarter or code better, it is just that they have made the same stupid mistake so many times that it is second nature to fix it.
    --Me, I just made it up

    The reasonable man adapts himself to the world; the unreasonable one persists in trying to adapt the world to himself. Therefore, all progress depends on the unreasonable man.
    --George Bernard Shaw

  11. #11
    aoeuhtns
    Join Date
    Jul 2005
    Posts
    581
    It's portable, simple, and endian-proof to use bitwise operators.

    Code:
    unsigned long x;
    
    unsigned char low_byte = x & 255;
    unsigned char second_byte = (x >> 8) & 255;
    unsigned char third_byte = (x >> 16) & 255;
    unsigned char high_byte = (x >> 24) & 255;

  12. #12
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    And it's even more portable if you use UCHAR_MAX instead of 255 and CHAR_BIT instead of 8 and sizeof instead of assuming 4 bytes per int.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  13. #13
    Registered User mitakeet's Avatar
    Join Date
    Jun 2005
    Location
    Maryland, USA
    Posts
    212
    How about this (tested on Solaris (bigendian) and Intel (little endian)):

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <limits.h>
    
    void printBits(unsigned char val){
        size_t i, end = sizeof(unsigned char) * CHAR_BIT;
        unsigned char tmp = (UCHAR_MAX / 2) + 1;
        for (i=0; i<end; i++){
            if (tmp & val) putc('1', stdout);
            else putc('0', stdout);
            tmp >>= 1;
        }
    }
    
    int main(){
        unsigned long i, tmp, number = 0, x;
        char buf[BUFSIZ];
        const size_t numBytes = sizeof(unsigned long);
        unsigned char ByteBuf[sizeof(unsigned long)];
        
    
        while (1){
            printf("Please enter a number to convert to binary: ");
            fgets(buf, BUFSIZ, stdin);
            rewind(stdin);
            x = number = atol(buf);
            tmp = 0;
            for (i=numBytes; i>0; i--){
                ByteBuf[i-1] = (unsigned char)(x >> tmp);
                tmp += 8;
            }
            for (i=0; i<numBytes; i++){
                printBits(ByteBuf[i]);
                printf(" ");
            }
            printf("\n");
        }
        return 0;
    }
    Last edited by mitakeet; 07-13-2005 at 11:06 AM. Reason: Updated code based on Dave_Sinkula's comments

    Free code: http://sol-biotech.com/code/.

    It is not that old programmers are any smarter or code better, it is just that they have made the same stupid mistake so many times that it is second nature to fix it.
    --Me, I just made it up

    The reasonable man adapts himself to the world; the unreasonable one persists in trying to adapt the world to himself. Therefore, all progress depends on the unreasonable man.
    --George Bernard Shaw

  14. #14
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Why not use CHAR_BIT instead of 8?

    I think masking with UCHAR_MAX after a value has been cast to an unsigned char is redundant.


    [aside]I prefer size_t for the type of variables that receive a value from sizeof. (It keeps the linter quieter.) I also don't care to use sizeof on types when it is avoidable, but that's the way I am.[/aside]
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  15. #15
    Registered User mitakeet's Avatar
    Join Date
    Jun 2005
    Location
    Maryland, USA
    Posts
    212
    Well, I intended to use CHAR_BIT, but forgot. size_t is better syntax (i.e., more portable) and again an oversite. I agree that with the cast the mask is entirely redundant, though how you write portable code without sizeof is beyond me.

    Free code: http://sol-biotech.com/code/.

    It is not that old programmers are any smarter or code better, it is just that they have made the same stupid mistake so many times that it is second nature to fix it.
    --Me, I just made it up

    The reasonable man adapts himself to the world; the unreasonable one persists in trying to adapt the world to himself. Therefore, all progress depends on the unreasonable man.
    --George Bernard Shaw

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Frustated with mess table printing
    By benedicttobias in forum C Programming
    Replies: 6
    Last Post: 04-16-2009, 05:50 PM
  2. Replies: 2
    Last Post: 03-24-2006, 07:36 PM
  3. Switch/case Problems (long code in post)
    By Wraithan in forum C++ Programming
    Replies: 2
    Last Post: 12-01-2005, 05:40 PM
  4. getting a headache
    By sreetvert83 in forum C++ Programming
    Replies: 41
    Last Post: 09-30-2005, 05:20 AM
  5. My graphics library
    By stupid_mutt in forum C Programming
    Replies: 3
    Last Post: 11-26-2001, 05:05 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21