Rectangle 27 12

Packed conversion using SSE is by far the fastest method, since you can convert multiple values in the same instruction. ffmpeg has a lot of assembly for this (mostly for converting the decoded output of audio to integer samples); check it for some examples.

It is a good suggestion however I will caveat it by saying it assumes two things: - That you have an x86 processor with SSE (>PII) or SSE2 (>PIII) - That you in fact do want a truncation, not a rounding, conversion

Also note the limitation that this will of course not be an option for an 80-bit floating point value

c - What is the fastest way to convert float to int on x86 - Stack Ove...

c optimization x86 floating-point assembly
Rectangle 27 6

There is one instruction to convert a floating point to an int in assembly: use the FISTP instruction. It pops the value off the floating-point stack, converts it to an integer, and then stores at at the address specified. I don't think there would be a faster way (unless you use extended instruction sets like MMX or SSE, which I am not familiar with).

Another instruction, FIST, leaves the value on the FP stack but I'm not sure it works with quad-word sized destinations.

c - What is the fastest way to convert float to int on x86 - Stack Ove...

c optimization x86 floating-point assembly
Rectangle 27 29

The std::mbstowcs function is what you are looking for:

char text[] = "something";
 wchar_t wtext[20];
 mbstowcs(wtext, text, strlen(text)+1);//Plus null
 LPWSTR ptr = wtext;

--> ED: The "L" prefix only works on string literals, not variables. <--

mbstowcs_s()

@Olipro: This is "deprecated" only in the Windows world. The OP did not stated which platform he was targeting.

it's fairly implicit that the platform is Windows, but if you think otherwise, go ahead and prove me wrong.

@Olipro: what's the advantage of the _s versions? As far as I can tell, you pass another count parameter that indicates at most how many characters you want written out, but how does that help? You already specify the size of the output buffer in another argument, is this just for the sake of the terminating zero?

c++ - Convert char * to LPWSTR - Stack Overflow

c++ c string
Rectangle 27 16

It depends on if you want a truncating conversion or a rounding one and at what precision. By default, C will perform a truncating conversion when you go from float to int. There are FPU instructions that do it but it's not an ANSI C conversion and there are significant caveats to using it (such as knowing the FPU rounding state). Since the answer to your problem is quite complex and depends on some variables you haven't expressed, I recommend this article on the issue:

c - What is the fastest way to convert float to int on x86 - Stack Ove...

c optimization x86 floating-point assembly
Rectangle 27 11

The clean way to use mbstowcs is to call it twice to find the length of the result:

const char * cs = <your input char*>
  size_t wn = mbsrtowcs(NULL, &cs, 0, NULL);

  // error if wn == size_t(-1)

  wchar_t * buf = new wchar_t[wn + 1]();  // value-initialize to 0 (see below)

  wn = mbsrtowcs(buf, &cs, wn + 1, NULL);

  // error if wn == size_t(-1)

  assert(cs == NULL); // successful conversion

  // result now in buf, return e.g. as std::wstring

  delete[] buf;
setlocale(LC_CTYPE, "");

The advantage over the Windows MultiByteToWideChar is that this is entirely standard C, although on Windows you might prefer the Windows API function anyway.

I usually wrap this method, along with the opposite one, in two conversion functions string->wstring and wstring->string. If you also add trivial overloads string->string and wstring->wstring, you can easily write code that compiles with the Winapi TCHAR typedef in any setting.

[Edit:] I added zero-initialization to buf, in case you plan to use the C array directly. I would usually return the result as std::wstring(buf, wn), though, but do beware if you plan on using C-style null-terminated arrays.[/]

In a multithreaded environment you should pass a thread-local conversion state to the function as its final (currently invisible) parameter.

Here is a small rant of mine on this topic.

+1 for showing how to call the function twice to get the length of the output buffer

Cheers. In the privacy of my own thoughts, I actually use a variable-length array for buf, but I wanted to avoid that in the light of SO scrutiny :-)

codecvt
mbsrtowcs
wcsrtombs

c++ - Convert char * to LPWSTR - Stack Overflow

c++ c string
Rectangle 27 9

A commonly used trick for plain x86/x87 code is to force the mantissa part of the float to represent the int. 32 bit version follows.

The 64-bit version is analogical. The Lua version posted above is faster, but relies on the truncation of double to a 32-bit result, therefore it requires the x87 unit to be set to double precision, and cannot be adapted for double to 64-bit int conversion.

The nice thing about this code is it is completely portable for all platforms conforming to IEEE 754, the only assumption made is the floating point rounding mode is set to nearest. Note: Portable in the sense it compiles and works. Platforms other than x86 usually do not benefit much from this technique, if at all.

static const float Snapper=3<<22;

union UFloatInt {
 int i;
 float f;
};

/** by Vlad Kaipetsky
portable assuming FP24 set to nearest rounding mode
efficient on x86 platform
*/
inline int toInt( float fval )
{
  Assert( fabs(fval)<=0x003fffff ); // only 23 bit values handled
  UFloatInt &fi = *(UFloatInt *)&fval;
  fi.f += Snapper;
  return ( (fi.i)&0x007fffff ) - 0x00400000;
}

For unsigned integer it can be simpler: inline uint32_t toInt( float fval ) { static float const snapper = 1<<23; fval += snapper; return ((uint32_t)fval) & 0x007FFFFF; }

static float const snapper;
fval += 1<<23;

On x86 it is not slower, as the code generated is the same. There are no FPU instructions taking immediate arguments on x87.

c - What is the fastest way to convert float to int on x86 - Stack Ove...

c optimization x86 floating-point assembly
Rectangle 27 6

If you can guarantee the CPU running your code is SSE3 compatible (even Pentium 5 is, JBB), you can allow the compiler to use its FISTTP instruction (i.e. -msse3 for gcc). It seems to do the thing like it should always have been done:

Note that FISTTP is different from FISTP (that has its problems, causing the slowness). It comes as part of SSE3 but is actually (the only) X87-side refinement.

Other then X86 CPU's would probably do the conversion just fine, anyways. :)

c - What is the fastest way to convert float to int on x86 - Stack Ove...

c optimization x86 floating-point assembly
Rectangle 27 6

The Lua code base has the following snippet to do this (check in src/luaconf.h from www.lua.org). If you find (SO finds) a faster way, I'm sure they'd be thrilled.

lua_Number
/*
@@ lua_number2int is a macro to convert lua_Number to int.
@@ lua_number2integer is a macro to convert lua_Number to lua_Integer.
** CHANGE them if you know a faster way to convert a lua_Number to
** int (with any rounding method and without throwing errors) in your
** system. In Pentium machines, a naive typecast from double to int
** in C is extremely slow, so any alternative is worth trying.
*/

/* On a Pentium, resort to a trick */
#if defined(LUA_NUMBER_DOUBLE) && !defined(LUA_ANSI) && !defined(__SSE2__) && \
    (defined(__i386) || defined (_M_IX86) || defined(__i386__))

/* On a Microsoft compiler, use assembler */
#if defined(_MSC_VER)

#define lua_number2int(i,d)   __asm fld d   __asm fistp i
#define lua_number2integer(i,n)     lua_number2int(i, n)

/* the next trick should work on any Pentium, but sometimes clashes
   with a DirectX idiosyncrasy */
#else

union luai_Cast { double l_d; long l_l; };
#define lua_number2int(i,d) \
  { volatile union luai_Cast u; u.l_d = (d) + 6755399441055744.0; (i) = u.l_l; }
#define lua_number2integer(i,n)     lua_number2int(i, n)

#endif

/* this option always works, but may be slow */
#else
#define lua_number2int(i,d) ((i)=(int)(d))
#define lua_number2integer(i,d) ((i)=(lua_Integer)(d))

#endif

c - What is the fastest way to convert float to int on x86 - Stack Ove...

c optimization x86 floating-point assembly
Rectangle 27 4

This version, using the Windows API function MultiByteToWideChar(), handles the memory allocation for arbitrarily long input strings.

int lenA = lstrlenA(input);
int lenW = ::MultiByteToWideChar(CP_ACP, 0, input, lenA, NULL, 0);
if (lenW>0)
{
    output = new wchar_t[lenW];
    ::MultiByteToWideChar(CP_ACP, 0, input, lenA, output, lenW);
}

@Kerrek In the interests of brevity I omitted the code that calls free ;-)

I'd rather you leave it as it is than call free()! This is definitely a case for the celebrated delete[] expression :-)

c++ - Convert char * to LPWSTR - Stack Overflow

c++ c string
Rectangle 27 2

pHttpContext->GetRequest()->GetHeader("Accept", NULL);

returns a PCSTR data type.

But I need to feed the WriteEventViewerLog with header as a LPCWSTR, since one of the functions that I use inside the methods only accepts the string in that format.

First, let's clarify the meaning of these "obscure" Windows API string typedefs:

PCSTR:   const char *    
LPCWSTR: const wchar_t *

The difference is that PCSTR points to a char-based string; LPCWSTR points to a wchar_t-based string.

char-based strings can be of several "forms" (or encodings), e.g. simple ASCII, or Unicode UTF-8, or other "multi-byte" encodings.

In case of your header string, I assume it can be simple ASCII, or UTF-8 (note that ASCII is a proper subset of UTF-8).

wchar_t-based strings in Visual C++ are Unicode UTF-16 strings (and this is the "native" Unicode encoding used by most Win32 APIs).

So, what you have to do is to convert from a char-based string to a wchar_t-based one. Assuming that your char-based string represents a Unicode UTF-8 string (of which pure ASCII is a proper subset), you can use the MultiByteToWideChar() Win32 API to do the conversion.

Or you can use some helper classes to simplify the conversion task, for example ATL conversion helpers. In particular, the CA2W helper with the CP_UTF8 conversion flag can come in handy in your case:

#include <atlconv.h>  // for CA2W
...

// Get the header string in Unicode UTF-8
PCSTR header = pHttpContext->GetRequest()->GetHeader("Accept", nullptr);

// Convert the header string from UTF-8 to Unicode UTF-16
WriteEventViewerLog( CA2W(header, CP_UTF8) );

The use of CA2W solved the issue. I just had to #include <atlbase.h> #include <atlstr.h> in addition to atlconv.h to be able to use it.

string - Visual C++: Convert data type PCSTR to LPCWSTR - Stack Overfl...

c++ string winapi lpcstr lpcwstr
Rectangle 27 5

If you are converting it to/from a string at any point try using %0.16f instead of %f (or whatever precision you want instead of .16).

Also, use objectForKey instead of valueForKey (valueForKey is not intended to be used on dictionaries):

currentObject.red = [[attributeDict objectForKey:@"red"] floatValue];
objectForKey
valueForKey

Thanks, that works! Also thanks for the objectForKey: note, I usually keep a closer eye on those things.

objective c - Loss of precision converting 'float' to NSNumber, back t...

objective-c cocoa floating-point nsnumber
Rectangle 27 607

It is not a matter of how the number is stored, it is a matter of how you are displaying it. When converting it to a string you must round to the desired precision, which in your case is two decimal places.

NSString* formattedNumber = [NSString stringWithFormat:@"%.02f", myFloat];

%.02f tells the formatter that you will be formatting a float (%f) and, that should be rounded to two places, and should be padded with 0s.

%f = 25.000000
%.f = 25
%.02f = 25.00

I noticed that using %.2f actually returns 25.00 in your example and not 25. This is strange.

The way i always understood was that the number after the decimal point said how much decimals you got. So, .2f would indeed give 25.00, and .4f would give 25.0000.

25
@"%.f"
@"%.*f", decimalPlaces, number

Probably this will be a partial off-topic but I would add another format: %03.f = 025

objective c - Make a float only show two decimal places - Stack Overfl...

objective-c formatting floating-point
Rectangle 27 594

It is not a matter of how the number is stored, it is a matter of how you are displaying it. When converting it to a string you must round to the desired precision, which in your case is two decimal places.

NSString* formattedNumber = [NSString stringWithFormat:@"%.02f", myFloat];

%.02f tells the formatter that you will be formatting a float (%f) and, that should be rounded to two places, and should be padded with 0s.

%f = 25.000000
%.f = 25
%.02f = 25.00

I noticed that using %.2f actually returns 25.00 in your example and not 25. This is strange.

The way i always understood was that the number after the decimal point said how much decimals you got. So, .2f would indeed give 25.00, and .4f would give 25.0000.

25
@"%.f"
@"%.*f", decimalPlaces, number

Probably this will be a partial off-topic but I would add another format: %03.f = 025

objective c - Make a float only show two decimal places - Stack Overfl...

objective-c formatting floating-point
Rectangle 27 3

If you really care about the speed of this make sure your compiler is generating the FIST instruction. In MSVC you can do this with /QIfist, see this MSDN overview

You can also consider using SSE intrinsics to do the work for you, see this article from Intel: http://softwarecommunity.intel.com/articles/eng/2076.htm

c - What is the fastest way to convert float to int on x86 - Stack Ove...

c optimization x86 floating-point assembly
Rectangle 27 3

Since MS scews us out of inline assembly in X64 and forces us to use intrinsics, I looked up which to use. MSDN doc gives _mm_cvtsd_si64x with an example.

The example works, but is horribly inefficient, using an unaligned load of 2 doubles, where we need just a single load, so getting rid of the additional alignment requirement. Then a lot of needless loads and reloads are produced, but they can be eliminated as follows:

#include <intrin.h>
 #pragma intrinsic(_mm_cvtsd_si64x)
 long long _inline double2int(const double &d)
 {
     return _mm_cvtsd_si64x(*(__m128d*)&d);
 }
i=double2int(d);
000000013F651085  cvtsd2si    rax,mmword ptr [rsp+38h]  
000000013F65108C  mov         qword ptr [rsp+28h],rax

The rounding mode can be set without inline assembly, e.g.

_control87(_RC_NEAR,_MCW_RC);
float.h
_control87()

And, no, this will not work in 32 bits, so keep using the FISTP instruction:

_asm fld d
_asm fistp i

This is interesting, and appears to be correct, but in my tests the x64 compiler actually generates the exact same code (verified using a disassembler) for your code here and the MSDN example.

c - What is the fastest way to convert float to int on x86 - Stack Ove...

c optimization x86 floating-point assembly
Rectangle 27 4

I would say that the easiest way, if you have a buffer that is not a C string - convert it to string, and use the standard functions (atoi etc.). Usually it will not even require allocation of more memory, but only a copy of the current string.

well maybe I should say convert c chars into numeric types, but you know what I am trying to do

c - Convert strings specified by length (not NUL-terminated) to int/fl...

c string
Rectangle 27 4

I would say that the easiest way, if you have a buffer that is not a C string - convert it to string, and use the standard functions (atoi etc.). Usually it will not even require allocation of more memory, but only a copy of the current string.

well maybe I should say convert c chars into numeric types, but you know what I am trying to do

c - Convert strings specified by length (not NUL-terminated) to int/fl...

c string
Rectangle 27 2

I assume truncation is required, same as if one writes i = (int)f in "C".

If you have SSE3, you can use:

int convert(float x)
{
    int n;
    __asm {
        fld x
        fisttp n // the extra 't' means truncate
    }
    return n;
}

Alternately, with SSE2 (or in x64 where inline assembly might not be available), you can use almost as fast:

#include <xmmintrin.h>
int convert(float x)
{
    return _mm_cvtt_ss2si(_mm_load_ss(&x)); // extra 't' means truncate
}

On older computers there is an option to set the rounding mode manually and perform conversion using the ordinary fistp instruction. That will probably only work for arrays of floats, otherwise care must be taken to not use any constructs that would make the compiler change rounding mode (such as casting). It is done like this:

void Set_Trunc()
{
    // cw is a 16-bit register [_ _ _ ic rc1 rc0 pc1 pc0 iem _ pm um om zm dm im]
    __asm {
        push ax // use stack to store the control word
        fnstcw word ptr [esp]
        fwait // needed to make sure the control word is there
        mov ax, word ptr [esp] // or pop ax ...
        or ax, 0xc00 // set both rc bits (alternately "or ah, 0xc")
        mov word ptr [esp], ax // ... and push ax
        fldcw word ptr [esp]
        pop ax
    }
}

void convertArray(int *dest, const float *src, int n)
{
    Set_Trunc();
    __asm {
        mov eax, src
        mov edx, dest
        mov ecx, n // load loop variables

        cmp ecx, 0
        je bottom // handle zero-length arrays

    top:
        fld dword ptr [eax]
        fistp dword ptr [edx]
        loop top // decrement ecx, jump to top
    bottom:
    }
}

Note that the inline assembly only works with Microsoft's Visual Studio compilers (and maybe Borland), it would have to be rewritten to GNU assembly in order to compile with gcc. The SSE2 solution with intrinsics should be quite portable, however.

Other rounding modes are possible by different SSE2 intrinsics or by manually setting the FPU control word to a different rounding mode.

re inline assembly: yes Embarcadero (formerly Borland) does support it (both C++ and Delphi compilers do)

c - What is the fastest way to convert float to int on x86 - Stack Ove...

c optimization x86 floating-point assembly
Rectangle 27 56

CGFloat strFloat = (CGFloat)[str floatValue];

That's not a floating point number. The floating point primitive has a SINGLE decimal point, like decimal numbers in arithmetics.

NSString * str = @"1.12"; CGFloat strFloat = (CGFloat)[str floatValue];

Asmad, I pasted your code into Xcode, ran it, and placed a breakpoint and it works properly - i.imgur.com/kUXigNn.png

Note that this will return 0.0 if the string is not a number. You'll need an additional check to distinguish from a true "0" string input.

@StanJames sure, that's a given. I'm assuming that the user would perform the appropriate checks that should be performed while using NSStrings.

objective c - How to convert a string to float? - Stack Overflow

objective-c ios cocoa-touch nsstring floating-point
Rectangle 27 3

What you are doing invokes undefined behavior, variadic functions will convert floats to double and the undefined behavior comes in because void * is not compatible with double and so you can have no expectation as to the result. We can see this by going to the draft C99 standard section 7.15.1.1 The va_arg macro which says:

[...]If there is no actual next argument, or if type is not compatible with the type of the actual next argument (as promoted according to the default argument promotions), the behavior is undefined,[...]

o->d = va_arg(list, double)

and you have the format specifier so this should be possible:

"test string %f"
             ^^

c - Passing float as argument screws up value - Stack Overflow

c floating-point unions