how to convert a binary array with hex values into decimal string

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • khumayun
    New Member
    • Jan 2010
    • 11

    how to convert a binary array with hex values into decimal string

    i have a byte array that contains hex values. i want to convert 6 bytes of it into decimal values and display the result as a string.

    also when do i have to take the endianess into consideration?

    i have tried to basically do a direct assignment to unsigned long and i saw that it did convert it correctly but i did not use any endianess. although i still did not convert it into a string.

    when do i use endianess ( i am developing on unbuntu but i know i will have to port this to a sun box/hp box maybe). i did read somewhere that as long as the unsigned long size is <= 2 it should work on any box. is this true? if so why?

    your help would be greatly appreciated.
  • khumayun
    New Member
    • Jan 2010
    • 11

    #2
    BTW i am not using .net c++ so i cannot use bitconverter etc.

    Comment

    • Banfa
      Recognized Expert Expert
      • Feb 2006
      • 9067

      #3
      Code:
      #include <iostream>
      
      unsigned char myVar = 0xA0;
      
      std::cout << static_cast<int>(myVar) << std::endl;
      Endianness only makes a difference when you are directly accessing a array of bytes that represents some larger integer type, long for example.

      Endianness needs to be considered for any integer type T for which sizeof(T) > 1. For most platforms this is short int and long.

      Comment

      • donbock
        Recognized Expert Top Contributor
        • Mar 2008
        • 2427

        #4
        I don't think you need to worry about endianness unless you're doing one of the following:
        • Your program accesses the same data item sometimes via one type and sometimes via another, differently sized, type. For example, you have a 32-bit data item that is sometimes accessed as an unsigned long and sometimes as an array of unsigned chars.
        • You seek to access a data item that must also be accessible to a dissimilar system; that is, a system that is not guaranteed to be the same processor and compiler combination. For example, your PC is writing to a binary file that might be read by a Linux PC.
        • You are accessing memory-mapped I/O devices.

        Most programs don't do any of these things; so most programs don't have to worry about endianness.

        Comment

        • donbock
          Recognized Expert Top Contributor
          • Mar 2008
          • 2427

          #5
          You say "I have a byte array that contains hex values. I want to convert 6 bytes of it into decimal values and display the result as a string."

          Do you mean this?
          You have a sequence of six hex-ASCII characters that you want to print as an equivalent [24-bit] decimal number.

          Or do you mean this?
          You have a 6-byte [48-bit] binary number that you want to print as an equivalent decimal number.

          Or do you mean something else?

          Comment

          • khumayun
            New Member
            • Jan 2010
            • 11

            #6
            its the first part. i have a byte array that has hex values which i would like to convert to decimals.

            also, i will be using this on a 64bit machine and that means i can't do direct assingment like you see me doing. because a long on a 32bit vs a 64 bit will give different results.

            so using code like
            Code:
            char bytes[4] = {0x12, 0x23, 0xff, 0xed};
            long* p_long = reinterpret_cast<long*>(bytes);
            
            std::cout << std::hex << *p_long << std::endl;
            as an example i can then actually put that into the function
            *p_long = bswap_32(*p_lon g);

            and get the big endian or little endian as above.

            the problem i really have is that my bytes are more than 4...like say 6. now how do i do this.

            second how do i get the hex values into decimals using the aforementioned method.

            the pointer i have there is just 4 bytes. so if i get another pointer that is an array of pointers...seem s to get more confusing.

            your help would be appreciated.
            thanks
            Last edited by NeoPa; Jan 14 '10, 01:49 AM. Reason: Please use the [CODE] tags provided

            Comment

            • donbock
              Recognized Expert Top Contributor
              • Mar 2008
              • 2427

              #7
              No ... you mean it is the second part: you have a 6-byte [48-bit] binary number that you want to print as an equivalent decimal number.

              How should the bytes be combined to create the big integer? Basically, you need to unpack the bytes in an order consistent with how they went into the array. This is not necessarily the endianness of your processor/compiler.

              For example, suppose the byte array is this:
              unsigned char array[6] = { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66 };
              Do you expect the big integer to be 0x112233445566?

              Does your implementation have an integer type large enough to hold a 48-bit integer (ie, do you have long long)? If so, this is a simple problem; if not, then this is a hard problem.

              By the way ... stop using "plain" char!
              This must be done with unsigned char.

              Comment

              • khumayun
                New Member
                • Jan 2010
                • 11

                #8
                i just wrote up that as a quick example. but essentially, i have
                byte output[somesize] that has hexadecimal values. i want to first convert this into decimal and then display x amount of digits.

                i am working on a 32bit system BUT will be most likely porting this to a 64 bit system.. which means that I can't just save this into a long. as saving this into a long on a 32bit system vs a 64 bit system would be different in the way the bytes will be read on each system.

                ofc, if i save it in a long (4 bytes) at least on the 32bit sytem I can get the first 4 bytes. perhaps I need a array of long pointers to store the other 2 bytes and byteswap so that it stores it as Big endian such that when this program runs on a 64 bit system it would read the values correctly.

                i am still very new to all of this but i believe this is what i understand so far.
                This is a program that does not use any files nor is using any over the network byte transfer. however, when this program runs on a 64bit system i think the way it will store the values could be MSB.

                does that help explain my situation a bit better?

                so in the example...
                0x112233445566 is how i would need to store it as so it stores it like that in a big endian system.

                I think i do have long long available. now..if i used an int32 then i could use the byteswap to make it into big endian but i think i would need to 2 longs (4 bytes each)to hold those values.

                something like long *p_long = reinterpret_cas t<long*> (bytes);

                then use *p_long = bswap(*p_long); to get the it into Big endian and in decimal format using the byteswap.h.

                however since that will only take 4 bytes i would maybe need an array of long pointers? to hold the other 2 bytes. not sure what to do after that then...theorizi ng this. not sure.

                Comment

                • donbock
                  Recognized Expert Top Contributor
                  • Mar 2008
                  • 2427

                  #9
                  1. Where does the array of hexadecimal bytes come from? How does a particular value get into it?

                  2. How long does this array of hexadecimal bytes need to persist? Does it exist for a longer interval than just while your program is running?

                  3. Agreed -- you should never use long for values larger than 32 bits even if a particular implementation happens to support more bits. I ask again ... can you use long long? long long is guaranteed to be at least 64 bits regardless of what operating system you use.

                  Comment

                  • khumayun
                    New Member
                    • Jan 2010
                    • 11

                    #10
                    i am basically taking input from console and doing some operations that output to a byte array which contains hexadecimal values something along the lines of below: the actual output is like 20bytes or 160bits

                    AFAB2591CFB70E7 7C7C417

                    basically i am calling a third party function that populates this byte array with the hexadecimal values.

                    essentially i am trying to store the whole byte array as a decimal value.

                    once i do that would the endianess come into play? like how i stored it? i know there is a byteswap function in the header i mentioned for 64 bits but when i try to use it it does not work. Instead of byte swapping it just prints 0.


                    sample test code:
                    Code:
                    #include <iostream>
                    #include "byteswap.h"
                    #include "stdlib.h"
                    
                    using namespace std
                    
                    ;
                    
                    int main()
                    {
                    char bytes[6] = {0x12,0x23,0xff,0xed,0x22,0x34};
                    
                    //long *p_long = reinterpret_cast<long*> (bytes);
                    
                    long long  *p_long = reinterpret_cast<long long*> (bytes);
                    
                    std::cout<<"hex="<<std::hex<<*p_long<<"LE"<<std::endl;
                    
                     *p_long = bswap_64(*p_long);
                    
                    std::cout<<"hex="<<std::hex<<*p_long<<"BE"<<std::endl;
                    
                    
                    
                    return 0;
                    }
                    Last edited by NeoPa; Jan 14 '10, 01:52 AM. Reason: Please use the [CODE] tags provided

                    Comment

                    • khumayun
                      New Member
                      • Jan 2010
                      • 11

                      #11
                      the only other thing i am thinking is with 20 bytes i would need an array of long long pointers and incrementing and keeping track of the pointers via sizeof(long) is not something i have done before. tips on using that would be appreciated.

                      Comment

                      • donbock
                        Recognized Expert Top Contributor
                        • Mar 2008
                        • 2427

                        #12
                        Lets start over and try to clearly identify the input.

                        There is no such thing as "hexadecima l values". The byte array contains binary values, hex-string values, decimal-string values, or something else. Consider the 4-byte value 0x12345678 (which is decimal 305419896). Does the byte array contain:
                        • binary: 0x12, 0x34, 0x56, 0x78 (with leading zeroes)
                        • hex-string: "12345678"
                        • decimal-string: "305419896"


                        Note: for ASCII character encoding the two strings would be:
                        • hex-string: 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x00
                        • decimal string: 0x33, 0x30, 0x35, 0x34, 0x31, 0x39, 0x38, 0x39, 0x36, 0x00


                        Instead of strings you might have character arrays that are padded with leading zero characters or with leading/trailing whitespace characters.

                        Comment

                        • khumayun
                          New Member
                          • Jan 2010
                          • 11

                          #13
                          ok my input from console is a hexadecimal value stored as a string.
                          i take that string and put it in a byte array. The api requires that i send it this byte array and it in return outputs its values as hex string. 2edab14fab etc.

                          The output byte array is initialized with 0x00 and this byte array is populated with the hex string which i can printf to screen with the %2.2x notation.

                          for example
                          byte output[some constant size];
                          memset(output,0 x00,some constant size);

                          so the string you saw earlier is a hex string in an output byte array.
                          this is the array that i am trying to store in such a manner that i can get decimal values for that hex string and then i will later ouput say 6 decimals on the screen.

                          Comment

                          • khumayun
                            New Member
                            • Jan 2010
                            • 11

                            #14
                            by hexadecimal value i mean...0-9 and Aa-Ff

                            Comment

                            • NeoPa
                              Recognized Expert Moderator MVP
                              • Oct 2006
                              • 32633

                              #15
                              Khumayun,

                              I think the point Don was trying to make was that the values are neither intrinsically hexadecimal, nor intrinsically string nor binary nor decimal. The values are values. They may be interpreted in a number of different ways depending on the software or human reading them, but they are not stored as hex values.

                              While this may be a small point generally, using incorrect terminology does cause the question you are trying to ask to be a lot harder to understand. One has to keep asking oneself - "Does this fail to make sense because of the wording, or because the OP (yourself) doesn't know what they're talking about generally?" "What do I think the OP is trying to say?"

                              So you see, the correct wording can be very important. I find this becomes more important the more technically intricate the question is. Attention to detail is so important for coders generally. This is certainly true when trying to convey a problem to somebody else.

                              Comment

                              Working...