Thread: typecasting

  1. #1
    Registered User
    Join Date
    May 2005
    Posts
    8

    typecasting

    hello! how can i convert unsigned char a[4] to unsigned long. Point is that i need to convert pixel, wich is defined as long to four subpixels and then back again.

  2. #2
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    The IMO simplest way is using a union:
    Code:
    union
    {
      unsigned char a[4];
      unsigned long l;
    } conv;
    Just assign to one, read the other.

    The other way is casting pointers:
    Code:
    unsigned long l = *reinterpret_cast<unsigned long *>(a);
    The third way uses shifts (this is the one where you can control endianness):
    Code:
    unsigned long l = a[0] | a[1] << 8 | a[2] << 16 | a[3] << 24;
    In all cases, remember that on my Athlon64, gcc will have 8-byte longs, so the result might not be what you expect. If your compiler has it, include <stdint.h> and use uint32_t instead. This header is part of the C99 standard. If it doesn't have it, or you just want to be portable, include <boost/cstdint.hpp> from the Boost libraries. It defines the same types, but in the boost namespace.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  3. #3
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    Code:
       unsigned long num;
    
       num = *reinterpret_cast< unsigned long * >(&a);

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Pointer Arithmetic and Typecasting
    By pobri19 in forum C Programming
    Replies: 2
    Last Post: 03-19-2009, 11:06 PM
  2. c and c++ style typecasting confusion
    By vaibhav in forum C++ Programming
    Replies: 14
    Last Post: 08-30-2005, 07:29 AM
  3. typecasting
    By sreetvert83 in forum C++ Programming
    Replies: 7
    Last Post: 07-22-2005, 01:55 PM
  4. Typecasting a void* to a function pointer
    By Procyon in forum C++ Programming
    Replies: 2
    Last Post: 01-14-2004, 05:43 PM
  5. typecasting
    By JaWiB in forum C++ Programming
    Replies: 14
    Last Post: 06-01-2003, 10:42 PM