-2

There is no compile error. However, the results are not expected. My suspicion is that the casting long to unsigned short int is causing the error. How can I safely cast long to a short for Hex? [Requiriments: Convert a row of string (which has numbers) to unsigned short int] Thanks!

unsigned short int str_to_bin (char* instr_bin_str) {
    unsigned short int i = 0;
    long j;
    char* ptr;

    j = strtol (instr_bin_str, &ptr, 10);

    if (j == 0) {
        fprintf (stderr, "error6: str_to_bin() failed");
        return 6;
    }

    i = (unsigned short) j;
    printf("State: 0x%X \n", i);

    return i;
}  
  • 1
    What is your input, expected output, and actual output? – dbush Apr 01 '18 at 17:41
  • 1
    Note that if you don't intend to use `ptr`, you can just pass `NULL` to `strtol` instead. – Oliver Charlesworth Apr 01 '18 at 17:43
  • If the given string is: 0001001000000001, then the output should be 0x1201 (by the printf). However, I am getting 0xDA01. –  Apr 01 '18 at 17:44
  • 2
    If the input string is binary, then `10` isn't the correct thing to be using. – Oliver Charlesworth Apr 01 '18 at 17:47
  • 2
    You literally write `strtol (instr_bin_str, &ptr, 10)`, where `10` means "base-10", or _decimal_, and expect it to treat the input as binary... – ForceBru Apr 01 '18 at 17:50
  • That was a bad example, my bad! Would casting long to a short not lose bits? I was wondering if this is safe practice to convert long to short. Are there safer alternatives? –  Apr 01 '18 at 18:07
  • Since a `short` is typically 16 bits long and a `long` is typically 32 or 64 bits. You can’t store all the bits from `strtol()` in a short in general. – Jonathan Leffler Apr 01 '18 at 18:33

1 Answers1

1

The string you're passing in is the binary representation of a number. However, when you're calling strtol you pass in 10 for the third parameter, which means it expects a string in decimal representation.

If you're expecting binary, you need to tell strtol to expect that:

j = strtol (instr_bin_str, &ptr, 2);
dbush
  • 205,898
  • 23
  • 218
  • 273