0

I am sending byte arrays between a TCP socket server & client in C. The information that I am sending is a series of integers.

I have it working, but because I am not too conversant with C, I was wondering if anyone could suggest a better solution, or at least to look and tell me that I'm not being too crazy or using outdated code with what I'm doing.

First, I generate a random decimal value, let's say "350". I need to transmit this over the socket connection as a hex byte array. It is decoded back to its decimal value at the other end.

So far, I convert it to hex this way:

unsigned char hexstr[4];
sprintf(hexstr, "%02X", numToConvert);  \\ where numToConvert is a decimal integer value like 350

At this point, I have a string in hexstr that's something like "15E" (again, using the hex value of 350 for an example).

Now, I need to store this in a byte array so that it looks something like: myArray = {0X00, 0X00, 0X01, 0X5E};

Obviously I can't just write: myArray = {0X00, 0X00, 0X01, 0X5E} because the values will be different every time, since a new random number is generated every time.

Currently, I do it like this (pseudocode because the string manipulation part is irrelevant but long):

lastTwoChars = getLastTwoCharsFromString(hexstr); // so lastTwoChars would now contain "5E"

Then (actual code):

sscanf(lastTwoChars, "%0X", &res); // now the variable res contains the byte representation of lastTwoChars, is my understanding

Then finally:

myArray[3] = res;

Then, I take the next two rightmost chars from hexstr (again, using the sample value of "15E", this would be "01" -- if there's only 1 more character, as in this case "1" was the only character left after taking out "5E" from "15E", I add 0s to the left to pad) and convert that the same way using sscanf, then insert into myArray[2]. Repeat for myArray[1] and myArray[0].

Then I send the array using write().

So, after hours of plugging away at it, this all does work... but because I don't use C very much, I have a nagging suspicion that there's something I am missing in all this. Can anyone comment if what I'm doing seems OK, or there's something obvious I'm using improperly or neglecting to use?

3
  • 1
    Are you attempting to encode the number as a printable ASCII string, or just transmit the number as four bytes, binary encoded? Commented Apr 14, 2014 at 22:10
  • Your code looks correct, but it's a bit hard to tell, because you don't show much code. Instead of sscanf you can use the somewhat simpler strtol and instead of sprintf you can use itoa. Commented Apr 14, 2014 at 22:10
  • I'm just trying to convert and transmit the number to an array of bytes with a length of 4. In C#, I would do this with: byte[] bytes = BitConverter.GetBytes(number); -- where number is a uint. That's how I did do it in C#, and now I'm redoing it in C.
    – minae
    Commented Apr 14, 2014 at 22:29

3 Answers 3

1
#include <stdio.h>
#include <limits.h>

int main(){
    unsigned num = 0x15E;//num=350
    int i, size = sizeof(unsigned);
    unsigned char myArray[size];
    for(i=size-1;i>=0;--i, num>>=CHAR_BIT){
        myArray[i] = num & 0xFF;
    }
    for(i=0;i<size;++i){
        printf("0X%02hhX ", myArray[i]);//0X02X
    }
    printf("\n");
    return 0;
}
18
  • "unsigned num"? Can you do that? Also, to be clear, 0X15E isn't meant to be a hardcoded value.
    – minae
    Commented Apr 14, 2014 at 22:31
  • @mrrrow unsigned num is just fine. Commented Apr 14, 2014 at 22:35
  • @mrrrow ,I can be omitted int.
    – BLUEPIXY
    Commented Apr 14, 2014 at 22:35
  • Can you do it like this, or does it need the 0x?: unsigned num = 15E
    – minae
    Commented Apr 14, 2014 at 22:37
  • 1
    @mrrrow It(0x) is required to hexadecimal constant.
    – BLUEPIXY
    Commented Apr 14, 2014 at 22:38
1

On the transmit side, convert a 32-bit number to a four byte array with this code

void ConvertValueToArray( uint32_t value, uint8_t array[] )
{
    int i;

    for ( i = 3; i >= 0; i-- )
    {
        array[i] = value & 0xff;
        value >>= 8;
    }
}

On the receive side, convert the byte array back into a number with this code

uint32_t ConvertArrayToValue( uint8_t array[] )
{
    int i;
    uint32_t value = 0;

    for ( i = 0; i < 4; i++ )
    {
        value <<= 8;
        value |= array[i];
    }

    return( value );
}

Note that it's important not to use generic types like int when writing this kind of code, since an int can be different sizes on different systems. The fixed-sized types are defined in <stdint.h>.

Here's a simple test that demonstrates the conversions (without actually sending the byte arrays over the network).

#include <stdio.h>
#include <stdint.h>

int main( void )
{
    uint32_t input, output;
    uint8_t byte_array[4];

    input = 350;
    ConvertValueToArray( input, byte_array );

    output = ConvertArrayToValue( byte_array );
    printf( "%u\n", output );
}
4
  • Thank you, that helped a lot as well. I'm curious, in BluePixy's solution, they used code pretty similar to yours, but a char array versus an int array. Why did you choose to go with an int array for your solution? (I ended up going with the char array because it turned out easier for me to print the contents of the char array than the int array, but that's probably only because I don't know how to do it with the int array.)
    – minae
    Commented Apr 15, 2014 at 1:03
  • In the C programming language, the built-in types (int, char, etc) do not have well defined sizes. For example, an int could be 16, 32, or 64 bits, depending on the compiler and system hardware. Using the types in <stdint.h> allows you to specify the exact size of a variable. For example, uint8_t is an unsigned value with 8 bits. On almost all systems, uint8_t is the same as unsigned char, and so you can use an uint8_t anywhere you would use an unsigned char. Commented Apr 15, 2014 at 1:12
  • One more question if you don't mind: Do you think it's always better to use uint32_t for example instead of an int? Say you're doing a for loop that goes from i=0; i < 10. Do you still think it's useful to use "uint32_t i;" to declare i, instead of just "int i" which is more readable? I.e. should I use these types indiscriminately? Or do you mean only that it's useful to use the stdint.h types in certain situations, such as when doing things like byte conversions where you don't know what might be in the byte?
    – minae
    Commented Apr 16, 2014 at 17:31
  • @mrrrow In general, I prefer to avoid the stdint.h types because the type names are, shall we say, messy. So when writing a simple for loop, I'll declare i as int. But there are situations where you need to guarantee that a variable is a certain size. A few examples that come to mind, 1) sending data across a network, 2) graphics routines, e.g. writing directly to a pixel buffer, 3) direct hardware access, e.g. writing device drivers. In all of these, the size of the variable and byte ordering are important, and need to be controlled. That's where the stdint.h types come in handy. Commented Apr 16, 2014 at 20:54
0

If your array is 4-byte aligned (and even if it isn't on machines that support unaligned access), you can use the htonl function to convert a 32-bit integer from host to network byte order and store the whole thing at once:

#include <arpa/inet.h> // or <netinet/in.h>

...

    *(uint32_t*)myArray = htonl(num);
7
  • You can avoid the alignment issue by doing uint32_t temp = htonl(num); memcpy(myArray, &temp, 4);
    – M.M
    Commented Apr 14, 2014 at 23:33
  • I thought htonl was just for flipping the order of bytes in a long, as necessary for little endian/big endian. Are you saying it can also be used to convert a 32-bit integer to byte array? Is there any documentation you can point me to about it? Thank you.
    – minae
    Commented Apr 15, 2014 at 0:50
  • Memory is just a big array of bytes, so a 32-bit integer, when stored in memory, is an array of 4 bytes. You just need to get the bytes in the correct (network) order.
    – pat
    Commented Apr 15, 2014 at 2:23
  • You are saying I can use this instead of the solutions involving bit shifting suggested above?
    – minae
    Commented Apr 15, 2014 at 5:12
  • Yes, try it out and see for yourself!
    – pat
    Commented Apr 15, 2014 at 14:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.