Jedi Engineer
Jedi Engineer

Reputation: 493

Convert unsigned short to char

I know there's other posts like this but I think mine is different. I have a group of numbers I wish to display. However, it's saved as unsigned short. As it's given to me from a network buffer, all my data is unsigned short format. So for a serial number starting with "ABC-" the two unsigned shorts will be holding 0x4142 and 0x432D (Already in ASCII format). I need to convert those to type char to display using printf and %s, but for the rest of my system, they need to remain as an unsigned short. This is what I've tried so far, but the output is blank:

unsigned char * num[3];

num[0] = (unsigned char*)(SYSTEM_N >> 8);
num[1] = (unsigned char*)(SYSTEM_N & 0x00FF);
printf("System Number: %s \r\n", num);

Can anyone shed some light on this for me? Thanks!

Upvotes: 2

Views: 25573

Answers (3)

MC93
MC93

Reputation: 799

A general solution might be something like this, assuming ushort_arr contains the unsigned shorts in an array and ushort_arr_size indicates its size.

char *str = malloc(ushort_arr_size * 2 + 1); 
// check if str == NULL

int j = 0;
for (int i = 0; i < ushort_arr_size; i++) {
    str[j++] = ushort_arr[i] >> 8;
    str[j++] = ushort_arr[i];
}
str[j] = '\0';

printf("string is: %s\n", str);

free(str);

Though perhaps this might be more effective without the memory management, if you only want to print it once:

for (int i = 0, j = 0; i < ushort_arr_size; i++) {
    putchar(ushort_arr[i] >> 8);
    putchar(ushort_arr[i] & 0xFF);
}

Upvotes: 0

Weather Vane
Weather Vane

Reputation: 34575

There are several errors: 1) array is too short, 2) defining the array as an array of pointers and 3) not terminating the string.

#include <stdio.h>

int main (void)
{
    unsigned short system_m = 0x4142;
    unsigned short system_n = 0x432D;
    unsigned char num[5];

    num[0] = system_m >> 8;
    num[1] = system_m & 0xFF;
    num[2] = system_n >> 8;
    num[3] = system_n & 0xFF;
    num[4] = '\0';
    printf("System Number: %s \r\n", num);

    return 0;
}

EDIT alternatively if you don't want to keep the string, just display the information with this:

#include <stdio.h>

int main (void)
{
    unsigned short system_m = 0x4142;
    unsigned short system_n = 0x432D;
    printf("System Number: %c%c%c%c \r\n",
           system_m >> 8, system_m & 0xFF, system_n >> 8, system_n & 0xFF);
    return 0;
}

Program output:

System Number: ABC-

Upvotes: 7

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

You probably meant to write

unsigned char num[3];

as you have it, you declare an array holding three char* pointers.

Also don't forget to set the closing NUL character, before printing:

num[2] = '\0';

Upvotes: 2

Related Questions